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
Find the Highest Altitude INPUT P0 P1 P2 P3 P4 P5 0 -3 -2 3 0 1 gain[] array: -3 1 5 -3 1 [0] [1] [2] [3] [4] ALGORITHM STEPS 1 Initialize curr=0, max=0 2 Loop through gain[] Add each gain to curr 3 Track maximum max = max(max, curr) 4 Return max Highest altitude found Iteration Trace: i gain[i] curr max - - 0 0 0 -3 -3 0 1 1 -2 0 2 5 3 3 3 -3 0 3 4 1 1 3 FINAL RESULT Highest Point! 0 3 Output: 3 OK - Max altitude = 3 Key Insight: Track running sum (prefix sum) of altitude gains while keeping track of the maximum. Start at altitude 0, add each gain to get current altitude, update max when current exceeds it. Time: O(n) | Space: O(1) - Single pass through the array with constant extra space. TutorialsPoint - Find the Highest Altitude | Optimal Solution
Asked in
Amazon 15 Google 12 Microsoft 8
99.7K 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