InterviewPrepKit

Home / Coding / Arrays & Hashing

Find the Highest Altitude

easy Original β†—
Solving tips
  • The array holds deltas and altitude i is the prefix sum, so carry one running total instead of re-summing (streaming prefix sum).
  • Track the max as you go in a single O(n) pass, O(1) space; max(0, max(accumulate(gain))) is the idiomatic one-liner.
  • Seed the max with 0 because the starting altitude counts; with all-negative gains the answer is 0.
  • Return the maximum altitude reached, not the final altitude, since the peak may occur mid-trip.

Problem

A cyclist starts a trip at altitude 0. The trip consists of n legs; you are given an integer array gain of length n, where gain[i] is the net change in altitude during leg i. After leg i the cyclist is at altitude gain[0] + gain[1] + ... + gain[i].

Return the highest altitude the cyclist ever reaches, including the starting altitude 0.

Examples

  • gain = [-5,1,5,0,-7] β†’ 1 β€” altitudes visited are 0, -5, -4, 1, 1, -6; the maximum is 1.
  • gain = [-4,-3,-2,-1,4,3,2] β†’ 0 β€” every prefix sum is negative, so the start (0) is the highest point.
  • gain = [2,2,-3,4] β†’ 5 β€” altitudes are 0, 2, 4, 1, 5; the maximum is 5.

Constraints

  • 1 <= len(gain) <= 100
  • -100 <= gain[i] <= 100

Tiny bounds β€” even quadratic passes β€” but the point of the exercise is the single-pass prefix-sum idea.

Think about it first

Hint 1 The altitude after leg i is a sum of which elements? Write out the sequence of altitudes for the first example.
Hint 2 Do you need to recompute each altitude from scratch, or does altitude i follow from altitude i - 1 in O(1)?
Hint 3 Keep a running sum starting at 0, add each gain in order, and track the maximum value the running sum ever takes β€” remembering that the start itself counts.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.