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
Difficulty
and has an acceptance rate of about 85% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Prefix Sum
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Solved On The Same Day
- problem 724: Find Pivot Index
- problem 872: Leaf-Similar Trees
- problem 933: Number of Recent Calls
- problem 1207: Unique Number of Occurrences
- problem 2215: Find the Difference of Two Arrays
- problem 328: Odd Even Linked List
- problem 443: String Compression
- problem 649: Dota2 Senate
- problem 735: Asteroid Collision
- problem 875: Koko Eating Bananas
- problem 901: Online Stock Span
- problem 1161: Maximum Level Sum of a Binary Tree
- problem 1268: Search Suggestions System
- problem 1282: Group the People Given the Group Size They Belong To
- problem 1372: Longest ZigZag Path in a Binary Tree
- problem 1448: Count Good Nodes in Binary Tree
- problem 1456: Maximum Number of Vowels in a Substring of Given Length
- problem 1493: Longest Subarray of 1's After Deleting One Element
- problem 1647: Minimum Deletions to Make Character Frequencies Unique
- problem 1657: Determine if Two Strings Are Close
- problem 1926: Nearest Exit from Entrance in Maze
- problem 2095: Delete the Middle Node of a Linked List
- problem 2130: Maximum Twin Sum of a Linked List
- problem 2352: Equal Row and Column Pairs
- problem 2390: Removing Stars From a String
Extra
- 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