Find the Highest Altitude - Problem

A biker is going on a road trip consisting of n + 1 points at different altitudes. The biker starts at point 0 with altitude 0.

You are given an integer array gain of length n where gain[i] is the net gain in altitude between points i and i + 1 for all 0 <= i < n.

Return the highest altitude reached during the trip.

Input & Output

Example 1 — Basic Case
$ Input: gain = [-3,1,5,-3,1]
Output: 3
💡 Note: Altitudes: 0 → -3 → -2 → 3 → 0 → 1. The highest altitude reached is 3.
Example 2 — All Negative Gains
$ Input: gain = [-4,-3,-2,-1]
Output: 0
💡 Note: Starting altitude 0 is the highest since all gains are negative: 0 → -4 → -7 → -9 → -10.
Example 3 — All Positive Gains
$ Input: gain = [1,2,3]
Output: 6
💡 Note: Altitudes increase continuously: 0 → 1 → 3 → 6. Maximum is 6.

Constraints

  • n == gain.length
  • 1 ≤ n ≤ 100
  • -100 ≤ gain[i] ≤ 100

Visualization

Tap to expand
Biker's Altitude JourneyPoint 0Alt: 0Point 1Alt: -3Point 2Alt: -2Point 3Alt: 3 (MAX)Point 4Alt: 0Point 5Alt: 1-3+1+5-3+1Highest Altitude: 3
Understanding the Visualization
1
Input
Array of altitude gains between consecutive points
2
Process
Calculate altitude at each point using running sum
3
Output
Return the maximum altitude reached
Key Takeaway
🎯 Key Insight: Use prefix sum to calculate running altitude while tracking the maximum value encountered
Asked in
Amazon 15 Google 12 Microsoft 8
99.6K Views
Medium Frequency
~10 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen