Find the Highest Altitude

Easy

Topics
ArrayPrefix Sum

A biker starts at altitude 0. gain[i] is the net gain between point i and i+1. Return the highest altitude reached.

Example 1

gain·-5150-7
altitude0-5-411-6
The input is the change at each step, not the altitude, so the altitudes are its running sum — the second row. The highest of those is the answer, 1. The start counts: with every step a descent, the answer is the 0 you began at.
Top row is the per-step gain, offset so each altitude sits above the gain that produced it; the first altitude is the starting 0.
Input:  gain = [-5,1,5,0,-7]
Output: 1

Example 2

gain·-4-3-2-1432
altitude0-4-7-9-10-6-3-1
Input:  gain = [-4,-3,-2,-1,4,3,2]
Output: 0

Constraints

  • 1 <= gain.length <= 100
  • -100 <= gain[i] <= 100
Editorial — intuition, approach, complexity and pitfalls

Intuition

The list gives changes, not positions. Altitude at any point is the running sum of the gains so far, starting from 0, and we want the largest value that running sum ever reaches.

So this is a prefix-sum maximum, computed in one pass with two variables. The only thing to get right is that the starting altitude of 0 counts as a candidate — if every gain is negative, the answer is 0, not the least-negative prefix.

Approach

  1. height = 0, best = 0.
  2. For each gain: add it to height, then update best.

Dry Run

gain = [-5, 1, 5, 0, -7]

start                 height=0   best=0
-5                    height=-5  best=0
+1                    height=-4  best=0
+5                    height=1   best=1
+0                    height=1   best=1
-7                    height=-6  best=1

answer 1

gain = [-4,-3,-2,-1,4,3,2]  ->  highest is 0 at the start,
then the prefix climbs back to exactly 0 at the end; answer 0

Complexity

  • Time — O(n): one pass.
  • Space — O(1): two integers. Building the prefix array first would be O(n) space for the same answer.

Common Pitfalls

  • Initialising best to the first prefix rather than 0. The cyclist starts at altitude 0, which is a legitimate maximum when all gains are negative.
  • Returning the largest single gain instead of the largest cumulative altitude.
  • Updating best before adding the gain, which misses the final point.
  • Assuming the altitudes return to 0 at the end. The problem does not require it.

Full Solution — all languages

class Solution:
    def largestAltitude(self, nums):
        h = best = 0
        for g in nums:
            h += g
            best = max(best, h)
        return best
Asked at Cognizant
SensAI
Beta
Tap the mic to stop voice mode