Find the Highest Altitude
Difficulty: Easy · Pattern: Prefix Sum · LeetCode #1732
A biker starts at altitude 0. gain[i] is the net altitude change between point i and i+1. Return the highest altitude reached.
Examples
text
[-5, 1, 5, 0, -7] → 1 (altitudes 0, −5, −4, 1, 1, −6)
[-4, -3, -2, -1, 4, 3, 2] → 0Hints
- Altitudes are prefix sums of
gain, starting from 0.
Approach
Keep a running altitude and its maximum, initialized at 0 (the starting point counts). O(n), O(1) space.
Complexity
Time: O(n). Space: O(1).
Python solution
def largestAltitude(gain):
alt = best = 0
for g in gain:
alt += g
best = max(best, alt)
return bestJavaScript solution
function largestAltitude(gain) {
let alt = 0, best = 0;
for (const g of gain) { alt += g; best = Math.max(best, alt); }
return best;
}