Maximum Subarray (LeetCode 53): Solution and Explanation
Given an integer array, find the contiguous, non-empty subarray with the largest sum and return that sum.
Watch it run step by step
Try your own input and write the code →Intuition
The brute force tries every start and every end and sums the elements in between, which is O(n³), or O(n²) if you extend each start with a running total. To do better, think about subarrays by where they end. For each index i, what is the best sum of a subarray that ends exactly at i? Call it best(i). The answer to the whole problem is the largest best(i).
There are only two choices for a subarray ending at i: it is just nums[i] by itself, or it extends the best subarray ending at i - 1. Extending only makes sense if that earlier sum is positive. If the sum you are carrying is negative, it can only drag down whatever comes next, so you are better off dropping it and starting fresh at nums[i]. That single rule is Kadane's algorithm.
The reference code implements it with one running total, curSum. Before adding each new number, it resets curSum to 0 if it went negative, which is the same as starting a new subarray here. Then it adds the number and records the maximum seen so far. Initializing maxSub to nums[0] rather than 0 matters: if every number is negative, the answer is the largest single negative number, not 0, because the subarray must contain at least one element.
Approach: Kadane's algorithm
- Set
maxSub = nums[0]so an all-negative array returns its largest element, and setcurSum = 0. - Loop over each number
ninnums. - If
curSum < 0, reset it to 0, because a negative prefix would only lower any sum that extends it. - Add
ntocurSum; this is now the best sum of a subarray ending at the current element. - Update
maxSub = max(maxSub, curSum). - Return
maxSubafter the loop.
Step-by-step example
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
- Start with maxSub = -2, curSum = 0. n = -2 makes curSum = -2, and maxSub stays -2.
- n = 1: curSum is negative, reset to 0, then curSum = 1. maxSub = 1. n = -3: curSum = -2, maxSub stays 1.
- n = 4: reset the negative sum, curSum = 4. maxSub = 4.
- n = -1: curSum = 3. n = 2: curSum = 5, maxSub = 5. n = 1: curSum = 6, maxSub = 6.
- n = -5: curSum = 1. n = 4: curSum = 5. maxSub stays 6, so return 6, from the subarray [4, -1, 2, 1].
Code: Python, Java, C++
1class Solution:
2 def maxSubArray(self, nums: List[int]) -> int:
3 maxSub = nums[0]
4 curSum = 0
5
6 for n in nums:
7 if curSum < 0:
8 curSum = 0
9 curSum += n
10 maxSub = max(maxSub, curSum)
11 return maxSub1class Solution {
2 public int maxSubArray(int[] nums) {
3 int maxSub = nums[0];
4 int curSum = 0;
5
6 for (int n : nums) {
7 if (curSum < 0) {
8 curSum = 0;
9 }
10 curSum += n;
11 maxSub = Math.max(maxSub, curSum);
12 }
13 return maxSub;
14 }
15}1class Solution {
2public:
3 int maxSubArray(vector<int>& nums) {
4 int maxSub = nums[0];
5 int curSum = 0;
6
7 for (int n : nums) {
8 if (curSum < 0) {
9 curSum = 0;
10 }
11 curSum += n;
12 maxSub = max(maxSub, curSum);
13 }
14 return maxSub;
15 }
16};Time and space complexity
O(n)
Each element is visited once and handled with a constant number of operations.
O(1)
Only two running variables, curSum and maxSub, are kept.
Other approaches
Divide and conquer (time O(n log n), space O(log n))
Split the array in half; the best subarray lies entirely in the left half, entirely in the right half, or crosses the midpoint. The crossing case is found with two linear scans from the middle. It is the follow-up the problem mentions, but it is slower than Kadane.
Prefix sums (time O(n), space O(1))
The sum of nums[i..j] is prefix[j + 1] - prefix[i]. Scanning once while tracking the smallest prefix seen so far gives the best difference in linear time, which is Kadane viewed from another angle.
Common mistakes
- Initializing
maxSubto 0. For an all-negative array like [-3, -1, -2], that returns 0, which corresponds to an empty subarray that is not allowed. The answer is -1. - Resetting
curSumwhen the current element is negative rather than when the running sum is negative. A negative element can still be worth including if the sum before it is large enough, as -1 is in [4, -1, 2, 1]. - Updating
maxSubbefore adding the current element, which misses the subarray ending at that element. - Treating this as a subsequence problem. The elements must be contiguous, so you cannot just add up all positive numbers.
Frequently asked questions
What is Kadane's algorithm?
It scans the array once, keeping the best sum of a subarray ending at the current position. If that running sum becomes negative, it is discarded and a new subarray starts at the next element.
How does Maximum Subarray handle all negative numbers?
Because maxSub starts at nums[0] and is updated after every element, the result is the single largest element. The subarray must be non-empty, so 0 is never returned unless 0 is in the array.
Is Maximum Subarray a dynamic programming problem?
Yes. The state is the best sum ending at index i, and the transition is max(nums[i], best(i - 1) + nums[i]). Kadane's algorithm is that recurrence with the table reduced to one variable.
How do I return the subarray itself?
Track the index where the current run started, updating it whenever you reset curSum, and save the start and end whenever maxSub improves.