Maximum Subarray
Pattern: Kadane and subarray sums
Keep the best sum of a subarray that ends at the current index. Each new value either extends that run or starts a new one, and the answer is the best run seen.
The problem
Given an array of whole numbers, return the largest sum of a non-empty block of neighbouring elements. For example,
[-2, 1, -3, 4, -1, 2, 1, -5, 4] gives 6 (4 - 1 + 2 + 1), [5, 4, -1, 7, 8] gives 23 (the whole array), and
[-3, -1, -2] gives -1.
The function name maxSubArray matches LeetCode. Use the link above for the exact statement and limits.
Think first
- Fix the end of the block at index
i. What are the choices for the best block ending there? - When should a run be dropped and a new one started?
- What should the answer be when every value is negative?
Hints
Brute force, and why it fails
Try every block with a running sum: O(n²). Kadane's pass is O(n).
The key insight
The best block ending at i only depends on the best block ending at i - 1. One number carried forwards answers the
question for every end, and the best of those is the answer.
Dry run
| current | -2 |
|---|---|
| best | -2 |
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]. Start with current = best = -2, the first value.
The plan
current = nums[0], best = nums[0]
for i from 1 to n - 1:
current = max(nums[i], current + nums[i])
best = max(best, current)
return best
Complexity
- Time
O(n)- Space
O(1)
One pass with two numbers.
Edge cases
- All negative: the largest single value.
- One element: that element.
- Zeros, as in
[0, -1, 0]: 0.
I've built my logic, show the code
Java
class Solution {
public int maxSubArray(int[] nums) {
int best = nums[0];
int current = nums[0]; // best sum of a subarray that ends here
for (int i = 1; i < nums.length; i++) {
current = Math.max(nums[i], current + nums[i]); // extend the old run, or start again here
best = Math.max(best, current);
}
return best;
}
}C++
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int best = nums[0];
int current = nums[0]; // best sum of a subarray that ends here
for (int i = 1; i < static_cast<int>(nums.size()); i++) {
current = max(nums[i], current + nums[i]); // extend the old run, or start again here
best = max(best, current);
}
return best;
}
};Python
class Solution:
def maxSubArray(self, nums: list[int]) -> int:
best = current = nums[0] # current: best sum of a subarray that ends here
for v in nums[1:]:
current = max(v, current + v) # extend the old run, or start again here
best = max(best, current)
return bestCommon mistakes
- Starting
bestat 0, which returns 0 for[-3, -1, -2]. - Reaching for a sliding window. With negative values there is no rule for when to shrink it.
- Returning
currentinstead ofbest.