Find the Highest Altitude
Easy
Topics
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
altitude
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
altitude
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
height = 0,best = 0.- For each gain: add it to
height, then updatebest.
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 0Complexity
- 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
bestto 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
bestbefore 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 bestimport java.util.*;
class Solution {
public int largestAltitude(int[] nums) {
int h = 0, best = 0;
for (int g : nums) {
h += g;
best = Math.max(best, h);
}
return best;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int largestAltitude(vector<int>& nums) {
int h = 0, best = 0;
for (int g : nums) {
h += g;
best = max(best, h);
}
return best;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var largestAltitude = function(nums) {
let h = 0, best = 0;
for (const g of nums) {
h += g;
if (h > best) best = h;
}
return best;
};
Asked at
Cognizant