data-structures · beginner · ~15 min

Recursive array max

Find the maximum by comparing against the rest.

Challenge

Implement:

int array_max(const int *a, int n);

Return the maximum of a[0..n-1] (n >= 1), computed recursively.

Input format

Array a, length n>=1.

Output format

Maximum element.

Constraints

Handle negative values.

Starter code

#include <stddef.h>
/* Maximum of a[0..n-1] (n>=1), computed recursively. */
int array_max(const int *a,int n){ (void)a;(void)n; return 0; }

Common mistakes

Base case at n==0 (there is no max of nothing) instead of n==1.

Edge cases to handle

Single element is its own max.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.