Highest Altitude Reached on a Trip
Problem
Starting at altitude 0, you make a sequence of altitude changes (positive for gains, negative for losses). Return the highest altitude reached at any point in the trip, including the start.
Input
gain = [-5, 1, 5, 0, -7]Output
1Altitudes: 0, -5, -4, 1, 1, -6. Max = 1.
def highest_altitude(gain):
alt = best = 0
for g in gain:
alt += g
if alt > best: best = alt
return best
function highestAltitude(gain) {
let alt = 0, best = 0;
for (const g of gain) {
alt += g;
if (alt > best) best = alt;
}
return best;
}
class Solution {
public int highestAltitude(int[] gain) {
int alt = 0, best = 0;
for (int g : gain) {
alt += g;
if (alt > best) best = alt;
}
return best;
}
}
int highestAltitude(vector<int>& gain) {
int alt = 0, best = 0;
for (int g : gain) {
alt += g;
if (alt > best) best = alt;
}
return best;
}