1732. Find the Highest Altitude
Problem
A biker starts at altitude 0; gain[i] is the net altitude change between points i and i + 1. Return the highest altitude reached.
Example: [-5,1,5,0,-7] → 1 (altitudes 0, −5, −4, 1, 1, −6)
The altitudes are the prefix sums of gain, starting from 0; return the largest one (including the starting 0).
Complexity: O(n).
class Solution:
def largestAltitude(self, gain: List[int]) -> int:
return max(0, max(itertools.accumulate(gain)))
assert Solution().largestAltitude([-5, 1, 5, 0, -7]) == 1
assert Solution().largestAltitude([-4, -3, -2, -1, 4, 3, 2]) == 0
assert Solution().largestAltitude([3]) == 3
class Solution {
public int largestAltitude(int[] gain) {
int alt = 0, best = 0;
for (int g : gain) best = Math.max(best, alt += g);
return best;
}
}
func largestAltitude(gain []int) int {
alt, best := 0, 0 // the start (altitude 0) counts too
for _, g := range gain {
alt += g
best = max(best, alt)
}
return best
}