InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Find the Highest Altitude

easy Original ↗ 00:00

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

The bounds are small enough that a quadratic solution passes, but the intended approach is the single-pass prefix sum.

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug