basics · beginner · ~15 min

Maximum of an array

Track a running maximum.

Challenge

Find the largest value in an integer array.

Task

Implement int array_max(const int *a, int n) that returns the largest of the first n elements. You are guaranteed n >= 1. Seed your running maximum from a[0] (not 0) so all-negative arrays work. No main — the grader calls it.

Input

A pointer a to at least n ints, and the count int n (n >= 1).

Output

Returns the maximum element, as an int.

Example

array_max({3,1,4,1,5,9,2,6}, 8)   ->   9
array_max({-5,-2,-9}, 3)          ->   -2
array_max({42}, 1)                ->   42

Edge cases

  • A single-element array returns that element.
  • All-negative arrays must still return the largest (e.g. -2), so do not start the max at 0.

Input format

A pointer a to n ints, and the count int n (n >= 1).

Output format

The largest element, as an int.

Constraints

n >= 1. Initialise the max from a[0], not 0.

Starter code

int array_max(const int *a, int n) {
    /* TODO */
    return 0;
}

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