Maximum of an array
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
- Nothing in the six is bigger than 9.
9
Example 2
- Input
- arr = [-8, -3, -11]
- Output
- All three are negative, so the answer is the least negative of them.
-3
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]);Explanation
One pass carrying one value: the largest seen so far, replaced whenever something bigger appears.
- 1
maxstarts asarr[0], the 3, andiat position 1.arr[1]is 7, which is greater thanmax, somaxtakes it.30i7122934415max=3
7 > 3 → max = 7
- 2
arr[2]is 2, which is not greater thanmax, so theifdoes not fire and nothing is assigned.3071i22934415max=7
2 < 7 → max unchanged
- 3
arr[3]is 9, greater than 7, somaxtakes it. This is the value the function ends up returning.307122i934415max=7
9 > 7 → max = 9
- 4
arr[4]is 4 — smaller, so nothing changes.30712293i4415max=9
4 < 9 → max unchanged
- 5
arr[5]is 1, smaller again.ireaches the end, the loop stops andmaxis returned.3071229344i15max=9
return max = 9
More like this
All arrays & loops examples (10) →- FizzBuzz The classic warm-up — Fizz, Buzz, or the number.
- Two sum Remember every number you’ve seen; check for its complement.
- Product except self Everything to the left of a position, times everything to its right.
- Majority element Pair off disagreeing votes; the majority always survives.
- Merge intervals Sort by start, then either extend the last interval or begin a new one.
- Top K frequent Bucket values by their count, then read the buckets from the top.