Highest Altitude Reached on a Trip

easy array prefix sum

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.

Inputgain = [-5, 1, 5, 0, -7]
Output1
Altitudes: 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;
}
Time: O(n) Space: O(1)