A cyclist rides along a road that passes n + 1 points. The ride begins at point 0, which sits at altitude 0.
You get an array gain of length n. gain[i] is how much the altitude changes going from point i to point i + 1; a negative value means the road goes down. Return the greatest altitude reached at any point, the start included.
Example 1
Input: gain = [-2, 5, -1, -3] Output: 3 Why: the altitudes are 0, -2, 3, 2, -1
2 more examples and the constraints
Example 2
Input: gain = [-3, -1, -2] Output: 0 Why: the road only goes down, so the start is highest
Example 3
Input: gain = [4] Output: 4 Why: one climb from 0 to 4
Constraints
- 1 ≤ gain.length ≤ 100
- −100 ≤ gain[i] ≤ 100
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- List every altitudeO(n)
- Running altitudeO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100 gains | Verdict |
|---|---|---|---|
| List every altitude | O(n) | Passes; keeps an extra list | |
| Running altitude | O(n) | Best; one pass, two numbers |
n = length of gain.
Edge cases to test
- Every gain is negative.
[-3, -1, -2]returns 0: the start is the highest point. - One gain.
[4]returns 4 and[-7]returns 0. - Peak at the end. The last altitude can be the answer, so check it inside the loop, after adding the gain.
- Flat road. All zeros keep the altitude at 0 the whole way.
Common mistakes
- Starting
bestat the first altitude or at minus infinity, which misses the start at 0. - Returning the largest gain instead of the largest running sum.
- Returning the final altitude instead of the highest one.
How to talk through it
- 1Clarify. Does the starting point count? Can gains be negative or zero?
- 2Name the idea. The altitude at a point is the sum of the gains before it: a prefix sum.
- 3Give the list version. Build every altitude, then take the max. Say it uses O(n) memory.
- 4Drop the list. Keep a running altitude and the best so far, both starting at 0.
- 5Test out loud. Run an all-negative input and a peak on the last point before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?