Problem 1732

Abstract / Summary

Track altitude changes from a list of gains and losses to determine the highest point reached.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1732.py

class Solution:
    def largestAltitude(self, gain: List[int]) -> int:
        result = 0
        alt = 0
        for g in gain:
            alt += g
            result = max(result, alt)

        return result
9 lines | 220 bytes | submitted September 12, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 85% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Prefix Sum
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a method largestAltitude that computes the maximum altitude reached during a flight given a list of altitude changes (gain). The algorithm iterates through the list once, maintaining a running sum of altitude changes and tracking the highest altitude observed. The method returns this maximum altitude as an integer.

Key Steps

The method begins by initializing two variables, result and alt, both set to zero. result holds the highest altitude encountered so far, while alt represents the current altitude relative to the starting point.

result = 0
alt = 0

A for loop then processes each element g in the gain list. Inside the loop, the current altitude alt is updated by adding the current gain g. Immediately after the update, result is refreshed to be the larger of its current value and the new altitude alt. This ensures that after each iteration, result reflects the maximum altitude seen up to that point.

for g in gain:
    alt += g
    result = max(result, alt)

After the loop completes, the method returns the value stored in result, which now represents the overall highest altitude reached during the entire sequence of gains.

return result

Edge Cases Handled

The algorithm gracefully handles an empty gain list. In such a scenario, the loop body never executes, leaving both result and alt at their initial value of zero. Consequently, the method returns zero, correctly indicating that no altitude change occurred and the flight remained at the starting altitude.

When the list contains only negative values, the cumulative altitude alt will decrease with each iteration. However, because result is initialized to zero and only updated when a higher altitude is observed, the method will still return zero. This reflects the fact that the starting altitude (zero) remains the highest point when all subsequent changes are downward.

If the list includes a mixture of positive and negative gains, the running sum alt may rise and fall multiple times. The use of max(result, alt) after each update guarantees that any temporary peak is captured, even if later gains cause the altitude to drop below that peak.

Performance Optimizations

The implementation achieves optimal performance by using a single pass over the input list, avoiding any auxiliary data structures. By updating the running altitude in place and immediately comparing it to the current maximum, the code eliminates the need for a separate traversal to locate the peak after the cumulative sums are computed. This approach reduces overhead and keeps memory usage minimal, as only two integer variables are maintained throughout execution. The use of Python’s built-in max function provides a fast, low-level comparison without additional branching logic.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a little adventurer hiking up and down a hilly path. The numbers in the list are like steps that tell the hiker whether to go up if the number is positive or down if the number is negative.

The hiker starts at the very bottom where the height is zero. The first variable keeps track of the highest point reached during the journey, and it starts at zero because the hiker is already at that level. The second variable keeps track of where the hiker is currently standing at any moment.

As the hiker moves, the code looks at each step in the list one by one. The current altitude changes by the amount of that step. If the hiker goes up, the altitude number gets bigger, and if the hiker goes down, it gets smaller. After every single step, there is a quick check to see if the hiker is now higher than the highest point recorded so far. If the new spot is higher, that spot becomes the new record for the highest altitude. This continues until every step has been taken.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.30 | σ = 0.85

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python JS Java Go C PHP Rust
Progiez C++ Python Java
github black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
halfrost Go
haoel C++
JoshCrozier JS
Krazune C++
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
withaarzoo C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, Go, Java, JavaScript, PHP, Python, Rust
Progiez C++, Java, Python
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
halfrost Go
haoel C++
JoshCrozier JavaScript
Krazune C++
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
withaarzoo C++
YuriSpiridonov Python
35 links | 21 authors | 11 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

26 solutions   September 12, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality