#1732

Find the Highest Altitude

Easy
ArrayPrefix SumPrefix SumArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

We can compute the highest altitude in a single pass by maintaining a running sum of the gains. This is more efficient as we avoid repeated calculations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize `current_altitude` to 0 and `max_altitude` to 0.
  2. 2Step 2: Iterate through each gain in the array, updating `current_altitude` by adding the gain.
  3. 3Step 3: After updating, check if `current_altitude` is greater than `max_altitude` and update it if necessary.
  4. 4Step 4: Return `max_altitude` after processing all gains.
solution.py9 lines
1# Full working Python code
2
3def highestAltitude(gain):
4    current_altitude = 0
5    max_altitude = 0
6    for g in gain:
7        current_altitude += g
8        max_altitude = max(max_altitude, current_altitude)
9    return max_altitude

Complexity note: This complexity is linear because we only traverse the array once, updating our altitude and maximum altitude in constant time.

  • 1The highest altitude is determined by cumulative gains, which can be efficiently calculated using a running sum.
  • 2Understanding prefix sums can simplify many problems involving cumulative data.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.