Find the Highest Altitude - Problem

Imagine you're tracking a mountain biker's journey through a scenic route with varying elevations. The biker starts at sea level (altitude 0) and travels through n + 1 checkpoints, each at different heights.

You're given an array gain where gain[i] represents the net change in altitude between checkpoint i and checkpoint i + 1. A positive value means going uphill, while a negative value means going downhill.

Your mission: Find the highest altitude the biker reaches during their entire journey.

Example: If gain = [-5, 1, 5, 0, -7], the biker's altitude at each point would be: [0, -5, -4, 1, 1, -6], so the highest altitude reached is 1.

Input & Output

example_1.py — Basic Mountain Route
$ Input: gain = [-5, 1, 5, 0, -7]
Output: 1
💡 Note: The altitudes are [0, -5, -4, 1, 1, -6]. The highest altitude is 1.
example_2.py — Steady Climb
$ Input: gain = [-4, -3, -2, -1, 4, 3, 2]
Output: 0
💡 Note: The altitudes are [0, -4, -7, -9, -10, -6, -3, -1]. The highest altitude is 0 (starting point).
example_3.py — Single Step
$ Input: gain = [5]
Output: 5
💡 Note: The altitudes are [0, 5]. The highest altitude is 5.

Visualization

Tap to expand
Find the Highest Altitude: Biker's Journey0Alt: 0-5Alt: -5+1Alt: -4+5Alt: 1+0Alt: 1-7Alt: -6MAX: 1Algorithm: Prefix Sum Approachcurrent_altitude = 0, max_altitude = 0For each gain: current_altitude += gain, max_altitude = max(max_altitude, current_altitude)
Understanding the Visualization
1
Starting Point
Biker begins at altitude 0 (sea level)
2
Process Each Segment
Add each altitude gain/loss to current position
3
Track Maximum
Remember the highest altitude reached so far
4
Continue Journey
Process all segments while maintaining the maximum
Key Takeaway
🎯 Key Insight: We only need to track the running sum (current altitude) and the maximum value seen so far, making this an optimal O(n) solution using prefix sum technique.

Time & Space Complexity

Time Complexity
⏱️
O(n)

We iterate through the gain array exactly once, performing constant time operations

n
2n
Linear Growth
Space Complexity
O(1)

Only using two variables to track current and maximum altitude

n
2n
Linear Space

Constraints

  • n == gain.length
  • 1 ≤ n ≤ 100
  • -100 ≤ gain[i] ≤ 100
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
42.3K Views
Medium Frequency
~8 min Avg. Time
1.9K 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