Python 0053.py
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
sums = []
total = 0
for n in nums:
total = max(total, 0) + n
sums.append(total)
return max(sums)
Difficulty
and has an acceptance rate of about 54% (10+ million submissions).
Typical patterns to solve this problem:
- Array
- Divide And Conquer
- 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 class Solution with a method maxSubArray that computes the maximum sum of any contiguous sub-array within a list of integers. The algorithm follows a single-pass approach, maintaining a running total that is reset to zero whenever it becomes negative, and records each intermediate total in a list. The final result is obtained by selecting the largest value from that list.
Key Steps
Handling a Single-Element Input
if len(nums) == 1:
return nums[0]
When the input list contains exactly one element, the method returns that element immediately. This early exit avoids unnecessary processing and correctly handles the edge case where the only possible sub-array consists of the sole element, regardless of its sign.
Initializing Accumulators
sums = []
total = 0
Two variables are prepared before iterating over the input. sums will collect the cumulative totals after each iteration, while total holds the current running sum that may be extended or restarted.
Iterating Through the Numbers
for n in nums:
total = max(total, 0) + n
sums.append(total)
During each loop iteration the algorithm decides whether to continue the existing sub-array or start a new one. The expression max(total, 0) ensures that a negative running total is discarded, effectively resetting the sum to zero before adding the current element n. The updated total is then appended to sums, preserving the state after each step.
Selecting the Maximum Sum
return max(sums)
After processing all elements, the method returns the greatest value stored in sums. This value corresponds to the maximum sum achievable by any contiguous sub-array in the original list.
Edge Cases Addressed
The early return for a single-element list guarantees correct behavior when the input length is one, covering both positive and negative solitary values. The use of max(total, 0) inside the loop naturally handles sequences that contain long stretches of negative numbers; the running total is reset whenever it would otherwise decrease the potential sum, ensuring that sub-arrays starting after a negative dip are considered. Additionally, because every intermediate total is recorded, the algorithm correctly identifies the maximum sum even when the optimal sub-array consists of the final elements of the list.
Performance Optimizations
The method processes the input list in a single linear pass, updating the running total and storing each intermediate result without nested loops or repeated scans. By resetting the running total to zero instead of recomputing from scratch, the algorithm avoids redundant calculations. Storing the intermediate totals in a list allows the final maximum to be retrieved with a single built-in max call, which is efficiently implemented in Python. The early exit for a one-element list eliminates the overhead of list allocation and iteration for the simplest possible input.
ELI5 - Simplified Explanation
Imagine you have a long row of building blocks, and each block has a secret number written on it. Some numbers are big and happy, and some are small or even grumpy with minus signs. The goal is to pick a group of blocks that sit right next to each other so that all their numbers added together make the biggest treasure pile possible.
To do this, the computer walks down the row of blocks one by one. It keeps a running total of the numbers as it goes. If the total ever starts to get grumpy and drops below zero, the computer decides to leave that grumpy part behind and start fresh with the next block. It keeps track of every new total it finds by putting them into a special toy box. Once the computer has looked at every single block in the row, it peeks inside the toy box to see which total pile is the biggest one of all. That biggest pile is the winner.
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# | Rust | JS | Go | TS | ||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | AdelDaniel | Dart | ||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| bujosa | Python | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| muhammadfarhankt | Go | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| AdelDaniel | Dart | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| bujosa | Python | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| muhammadfarhankt | Go | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 121: Best Time to Buy and Sell Stock
- problem 152: Maximum Product Subarray
- problem 325: Maximum Size Subarray Sum Equals k
- problem 697: Degree of an Array
- problem 978: Longest Turbulent Subarray
- problem 1746: Maximum Subarray Sum After One Operation
- problem 1749: Maximum Absolute Sum of Any Subarray
- problem 2219: Maximum Sum Score of Array
- problem 2272: Substring With Largest Variance
- problem 2302: Count Subarrays With Score Less Than K
- problem 2321: Maximum Score Of Spliced Array
- problem 2496: Maximum Value of a String in an Array
- problem 2599: Make the Prefix Sum Non-negative
- problem 2600: K Items With the Maximum Sum
- problem 2606: Find the Substring With Maximum Cost
Solved On The Same Day
- problem 195: Tenth Line
- problem 56: Merge Intervals
- problem 78: Subsets
- problem 86: Partition List
- problem 89: Gray Code
- problem 90: Subsets II
- problem 98: Validate Binary Search Tree
- problem 179: Largest Number
- problem 456: 132 Pattern
- problem 473: Matchsticks to Square
- problem 542: 01 Matrix
- problem 916: Word Subsets
- problem 1930: Unique Length-3 Palindromic Subsequences
- problem 233: Number of Digit One
- problem 295: Find Median from Data Stream
- problem 315: Count of Smaller Numbers After Self
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