Maximum Subarray
LeetCode 53 · Medium · solution, intuition & step-by-step walkthrough
A negative prefix never helps a future subarray — reset it to 0.
This is how I solved Maximum Subarray (LeetCode 53), a medium problem from the Kadane pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Walk through the array carrying a running sum. Whenever that running sum turns negative it can only drag down whatever comes next, so throw it away and start fresh. The best sum seen along the way is the answer (Kadane's algorithm).
Approach
- 1
cur_sum = sum of the current candidate subarray; max_sum = best seen.
- 2
Add each number to cur_sum and update max_sum before any reset.
- 3
If cur_sum drops below 0, reset it to 0 so the next element starts a new subarray.
How I solved it
Kadane's algorithmPythonO(n) time · O(1) space
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
max_sum = float("-inf")
cur_sum =0
for num in nums:
cur_sum+=num
max_sum = max(max_sum,cur_sum)
if cur_sum<0:
cur_sum=0
return max_sumMaximum Subarray — FAQ
What is the intuition behind Maximum Subarray?
Walk through the array carrying a running sum. Whenever that running sum turns negative it can only drag down whatever comes next, so throw it away and start fresh. The best sum seen along the way is the answer (Kadane's algorithm).
How do you solve Maximum Subarray (LeetCode 53)?
1. cur_sum = sum of the current candidate subarray; max_sum = best seen. 2. Add each number to cur_sum and update max_sum before any reset. 3. If cur_sum drops below 0, reset it to 0 so the next element starts a new subarray.
What is the time and space complexity of Maximum Subarray?
Time: O(n). Space: O(1). (Accepted approach: Kadane's algorithm.)
What are common mistakes in Maximum Subarray?
Update max_sum before resetting, otherwise an all-negative array returns 0 instead of its largest element.