Find the largest element in an array by keeping track of the maximum value seen so far.
Problem Statement
Given an array of integers, find the largest element in the array.
Examples
Input: arr = [1, 8, 7, 56, 90]
Output: 90
Explanation: 90 is the largest element in the array.
Constraints
Standard constraints
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
š” Hint 1:
Think about maintaining a variable to track the maximum element seen so far.
š” Hint 2:
Initialize your max variable with the first element arr[0] and iterate from index 1 to the end.
š” Hint 3:
Compare each element with max. If the current element is greater, update max. Returns max at the end.
Editorial & Approach
Problem Overview & Intuition
To find the maximum element in an unsorted array, we must examine every element at least once. Sorting the array takes O(N log N), but a single linear scan keeps track of the maximum value encountered so far in optimal O(N) time.
Step-by-Step Approach
- Initialize a variable
maxwith the first element of the array:let max = arr[0];. - Iterate through the array from index
1toarr.length - 1. - At each step, if
arr[i] > max, updatemax = arr[i]. - After completing the loop, return
max.
Optimal Implementation (JavaScript)
function largestElement(arr) {
if (arr.length === 0) return -1;
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
Complexity Analysis
Time Complexity
O(N) ā single pass through the array.
Space Complexity
O(1) ā constant extra memory used.
Edge Cases & Corner Traps Handled
- Single element array: immediately returns arr[0].
- All negative values: correctly returns the least negative number.
- All identical values: correctly returns that value.