Python 1749.py
class Solution:
def maxAbsoluteSum(self, nums: List[int]) -> int:
result = 0
# 1,000,000th problem based on Kadane's algorithm
high = low = 0
for n in nums:
high = max(n, high + n)
low = min(n, low + n)
result = max(result, abs(high), abs(low))
return result
Difficulty
and has an acceptance rate of about 71% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
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 Solution class with a single method maxAbsoluteSum. The method receives a list of integers and returns the maximum absolute value that can be obtained from any sub-array sum. The algorithm is a compact adaptation of Kadane’s technique, simultaneously tracking the best positive sub-array sum and the most negative sub-array sum while updating the overall answer with the larger absolute value.
Key Steps
Initialization
The method starts by setting the accumulator variables to zero. result holds the best absolute sum seen so far, while high and low represent the current maximum and minimum sub-array sums ending at the current position.
result = 0
high = low = 0
Iteration Over the Input
A single pass over nums processes each element n. For each element the algorithm decides whether to extend the previous sub-array or to start a new sub-array at the current element. This decision is made separately for the maximum and minimum sums.
for n in nums:
high = max(n, high + n)
low = min(n, low + n)
high = max(n, high + n)chooses the larger between starting a new sub-array withnalone or extending the previous maximum sub-array by addingn.low = min(n, low + n)mirrors the logic for the minimum sub-array, selecting the smaller (more negative) sum.
Updating the Result
After adjusting high and low, the algorithm updates result with the greatest absolute value observed so far. Both the current maximum and minimum sums are considered because the absolute value of a large negative sum can exceed that of a positive sum.
result = max(result, abs(high), abs(low))
Final Return
When the loop finishes, result contains the maximum absolute sub-array sum, which is returned to the caller.
return result
Edge Cases Handled
The algorithm gracefully handles several edge conditions without additional checks:
- All Positive Numbers - The
highvariable continuously accumulates the sum of the entire array, whilelowremains non-negative. The absolute value ofhighdominates, yielding the sum of the whole array. - All Negative Numbers -
highnever grows beyond a single element because extending a negative sum would make it smaller. Meanwhile,lowaccumulates the most negative prefix, and its absolute value becomes the answer. - Mixed Signs with Zeroes - Zero values are treated like any other integer. When a zero appears,
highmay stay unchanged or restart, andlowmay similarly reset, ensuring that sub-arrays that cross zero are evaluated correctly. - Single-Element Input - The loop runs once, setting
highandlowto that element, andresultbecomes the absolute value of that element, which is the correct answer. - Empty List - Although the problem specification typically guarantees at least one element, the initialization of
resultto zero means that an empty list would return zero, a sensible default for the maximum absolute sum of no sub-arrays.
Performance Optimizations
The implementation achieves high efficiency through several deliberate choices:
- Single Pass - By updating
high,low, andresultwithin the same loop, the algorithm processes the input in O(n) time, where n is the length ofnums. No auxiliary data structures are allocated, keeping the memory footprint minimal. - In-Place Variable Reuse - The same variables are reused for each iteration, avoiding the creation of temporary lists or objects. This reduces garbage-collection pressure and improves cache locality.
- Avoidance of Conditional Branches - The use of
maxandminfunctions encapsulates the conditional logic for extending or restarting sub-arrays. Modern interpreters often optimize these built-in functions, leading to faster execution compared with explicitifstatements. - Absolute Value Computation Only When Needed - The algorithm computes
abs(high)andabs(low)only once per iteration, directly feeding them into themaxcall that updatesresult. This avoids redundant absolute-value calculations. - Early Result Initialization - Starting
resultat zero ensures that the first iteration immediately captures the absolute value of the first element, eliminating the need for a separate initialization step after the loop.
Overall, the code delivers a concise, high-performance solution for determining the maximum absolute sub-array sum.
ELI5 - Simplified Explanation
Imagine you have a long row of building blocks in front of you. Some blocks have positive numbers written on them, which means they make your pile grow taller. Other blocks have negative numbers, which means they take pieces away from your pile. This code acts like a tiny robot that walks along the row of blocks one by one to find the best possible pile.
As the robot picks up each block, it keeps track of two special piles at the same time. One pile explores how high it can grow by adding up the numbers, and the other pile explores how far down it can go into negative territory. Every time the robot picks up a new block, it checks its two piles. It decides if it should start a brand new pile with just the block it is holding or if it should add that block to the pile it was already building.
After checking those piles, the robot looks at the very biggest number it has seen so far. It uses a trick to turn any negative pile into a positive one just to see how big the number is inside. It keeps updating its memory with the biggest size it finds throughout the whole walk. By the time the robot reaches the very last block, it has already figured out which group of blocks created the largest difference from zero.
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 | Go | Rust | TS | ||||
| Progiez | C++ | Python | Java | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fsq | C++ | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| Shamik07 | Dart | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| wisdompeak | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fsq | C++ | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| Shamik07 | Dart | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 53: Maximum Subarray
Solved On The Same Day
- problem 1763: Longest Nice Substring
- problem 1653: Minimum Deletions to Make String Balanced
- problem 761: Special Binary String
- problem 968: Binary Tree Cameras
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