Find Maximum
Problem Statement
Given an array of integers, find and return the maximum value.
Function Signature:
function findMax(arr) {
// Your code here
}
Examples
| Input | Output | Explanation |
|---|---|---|
[3, 1, 4, 1, 5, 9, 2, 6] | 9 | 9 is the largest value in the array |
[-5, -2, -8, -1] | -1 | -1 is the largest (least negative) value |
[42] | 42 | Single element is the maximum |
[7, 7, 7, 7] | 7 | All elements are equal |
Constraints
- Array length: 1 ≤ arr.length ≤ 10,000
- Element values: -10⁹ ≤ arr[i] ≤ 10⁹
- Array is guaranteed to have at least one element
Interactive Editor
function findMax(arr) { // Your code here }
Tests: 6 total
Hints
Hint 1: The Approach
Track the largest value you've seen so far as you iterate. Compare each element to your current maximum and update when you find something larger.
Hint 2: Initialization
Initialize your maximum with arr[0], not 0. This handles negative numbers and single-element arrays correctly.
Solution
View Solution Explanation
function findMax(arr) {
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
Start with the first element as your maximum, then iterate through the rest. Update max whenever you find something larger.
Complexity: O(n) time, O(1) space.
Alternative: Math.max(...arr) works but can overflow the call stack on very large arrays.