Maximum of an array

Easy TimeO(n) SpaceO(1)

Given a non-empty array of numbers arr, return the largest value in it. The array is in no particular order, the values may be negative, and the largest may appear more than once — in which case that same value is still the answer.

Examples

Example 1

Input
arr = [3, 7, 2, 9, 4, 1]
Output
9
Nothing in the six is bigger than 9.

Example 2

Input
arr = [-8, -3, -11]
Output
-3
All three are negative, so the answer is the least negative of them.

The Code

function findMax(arr) {
  let max = arr[0];
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] > max) max = arr[i];
  }
  return max;
}
findMax([3, 7, 2, 9, 4, 1]);
Done
Step through findMax([3, 7, 2, 9, 4, 1]) call by call

Explanation

One pass carrying one value: the largest seen so far, replaced whenever something bigger appears.

  1. 1

    max starts as arr[0], the 3, and i at position 1. arr[1] is 7, which is greater than max, so max takes it.

    3
    0
    i
    7
    1
    2
    2
    9
    3
    4
    4
    1
    5

    max=3

    7 > 3 → max = 7

  2. 2

    arr[2] is 2, which is not greater than max, so the if does not fire and nothing is assigned.

    3
    0
    7
    1
    i
    2
    2
    9
    3
    4
    4
    1
    5

    max=7

    2 < 7 → max unchanged

  3. 3

    arr[3] is 9, greater than 7, so max takes it. This is the value the function ends up returning.

    3
    0
    7
    1
    2
    2
    i
    9
    3
    4
    4
    1
    5

    max=7

    9 > 7 → max = 9

  4. 4

    arr[4] is 4 — smaller, so nothing changes.

    3
    0
    7
    1
    2
    2
    9
    3
    i
    4
    4
    1
    5

    max=9

    4 < 9 → max unchanged

  5. 5

    arr[5] is 1, smaller again. i reaches the end, the loop stops and max is returned.

    3
    0
    7
    1
    2
    2
    9
    3
    4
    4
    i
    1
    5

    max=9

    return max = 9