Python 1800.py
class Solution:
def maxAscendingSum(self, nums: List[int]) -> int:
result = 0
prev = 0
have = 0
for n in nums:
if n > prev:
have += n
result = max(result, have)
else:
have = n
prev = n
return result
Difficulty
and has an acceptance rate of about 66% (300k+ submissions).
Typical patterns to solve this problem:
- Array
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 maxAscendingSum that receives a list of integers and returns the maximum sum of a contiguous strictly increasing sub-sequence. The algorithm walks through the input once, maintaining running totals for the current ascending segment and the best total seen so far. By updating these values in place, the solution achieves a concise and efficient traversal without auxiliary data structures.
Key Steps
The method begins by initializing three variables: result to store the best sum discovered, prev to remember the previous element, and have to accumulate the sum of the current ascending segment.
result = 0
prev = 0
have = 0
The core of the algorithm is a single for loop that iterates over each number n in the input list nums.
for n in nums:
if n > prev:
have += n
result = max(result, have)
else:
have = n
prev = n
Inside the loop, the condition n > prev determines whether the current element continues the strictly increasing trend. If it does, the element is added to have, and result is potentially updated with the larger of its current value and have. When the trend breaks, have is reset to the current element, effectively starting a new candidate segment. After handling the element, prev is updated to the current value for the next iteration.
Finally, the method returns the value stored in result, which represents the maximum sum of any strictly increasing contiguous sub-array encountered during the scan.
return result
Edge Cases Handled
The algorithm gracefully manages several boundary conditions without additional checks.
When the input list is empty, the loop body never executes, leaving result at its initial value of 0. The method therefore returns 0, which is a sensible default for the maximum sum of an absent segment.
If the list contains a single element, the first iteration treats the element as greater than the initial prev value (0). Consequently, have becomes that element, result is updated to the same value, and the method returns the element itself, correctly reflecting the only possible ascending segment.
For sequences that never increase (e.g., a non-increasing list), each iteration triggers the else branch, resetting have to the current element. The result variable is still updated because the max operation is performed only when an increase occurs; however, the initial result of 0 will be superseded by the first element when the loop processes it, ensuring the returned value equals the largest single element in the list.
When the list contains repeated values, the strict inequality n > prev prevents inclusion of equal numbers in the same segment. The reset in the else clause starts a new segment at the repeated value, thereby respecting the requirement for a strictly increasing sequence.
Performance Optimizations
The implementation achieves optimal performance through several deliberate choices.
All state is kept in a handful of scalar variables (result, prev, have), eliminating the need for additional containers such as temporary lists or stacks. This minimal memory footprint reduces pressure on the garbage collector and improves cache locality.
The single pass over nums ensures that each element is examined exactly once, avoiding redundant work. The use of the built-in max function for updating result leverages a highly optimized native operation.
By resetting have directly to the current element rather than recomputing a sum from scratch, the algorithm avoids repeated addition of the same values, which would otherwise increase the instruction count.
The straightforward control flow-an if/else block followed by a single assignment-allows the Python interpreter to execute the loop with minimal branching overhead, contributing to faster execution on typical data sets.
ELI5 - Simplified Explanation
Imagine a row of blocks with numbers written on them, all lined up in a long magic path. This computer code acts like a tiny robot that walks down the line of blocks from left to right. The robot is looking for the biggest group of numbers that are getting bigger and bigger, like steps going up a hill.
Whenever the robot sees a new number, it checks if that number is bigger than the one it just saw. If the number is bigger, the robot adds it to its special counting box because the path is still going up. If the new number is smaller, the robot knows the hill has ended, so it empties its box and starts a brand new group with that number.
As the robot moves along, it keeps track of the highest score it has ever seen in its box. Every time the number in the box grows larger than the best score it remembers, the robot updates its memory with that new winning total. It keeps doing this until it reaches the very end of the line of blocks.
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 | Java | C | Go | Rust | TS | |||||
| Progiez | C++ | Python | Java | |||||||||
| github | black-shadows | C++ | ||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| fsq | C++ | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| lkwq007 | Python | |||||||||||
| Shamik07 | Dart | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C, C++, Go, Java, Python, Rust, TypeScript | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| fsq | C++ | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| lkwq007 | Python | |||||||||||
| Shamik07 | Dart | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 2100: Find Good Days to Rob the Bank
- problem 2393: Count Strictly Increasing Subarrays
Solved On The Same Day
- problem 1837: Sum of Digits in Base K
- problem 1813: Sentence Similarity III
- problem 1824: Minimum Sideway Jumps
- problem 1770: Maximum Score from Performing Multiplication Operations
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