Maximum Subarray
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Given an integer array nums, find the non-empty contiguous subarray with the largest sum, and return that sum.
Understand the problem
- A contiguous subarray is a run of elements next to each other: in
[1, -3, 4],[-3, 4]is one, but[1, 4]isn't. - Non-empty means you must pick at least one element, even if every number is negative.
- You return the sum, not the subarray.
Example 1
Input: nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Output: 6[4, -1, 2, 1] sums to 6. Including the -1 is worth it, because the 2, 1 after it more than make up for it.
Example 2
Input: nums = [5, 4, -1, 7, 8]
Output: 23The whole array.
Example 3
Input: nums = [-3, -1, -2]
Output: -1Every number is negative, and the subarray can't be empty, so the best is the single largest: -1.
Constraints
1 <= nums.length <= 10^5-10^4 <= nums[i] <= 10^4
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Walk the array keeping a running sum; whenever the running sum becomes negative, throw it away and start fresh, because a negative start can only make what follows smaller.
The naive approach (and why it's slow)
Try every start and every end, summing as you go: O(n²). With 100,000 elements, that's about 5 billion additions.
The key insight: a negative prefix never helps
Walk the array and keep current: the best sum of a subarray that ends at the current element. At each new number x, there are only two options:
- Extend the previous subarray:
current + x. - Start fresh at
x: justx.
Extending is worse exactly when current is negative: adding a negative number to x only makes it smaller. So:
current = max(x, current + x) best sum ending here
best = max(best, current) best sum seen anywhereThis is called Kadane's algorithm.
Step by step
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]. Start both at nums[0] = -2:
x | Extend (current + x) | Start fresh (x) | current | best |
|---|---|---|---|---|
| -2 | (start) | -2 | -2 | |
| 1 | -1 | 1 | 1 | 1 |
| -3 | -2 | -3 | -2 | 1 |
| 4 | 2 | 4 | 4 | 4 |
| -1 | 3 | -1 | 3 | 4 |
| 2 | 5 | 2 | 5 | 5 |
| 1 | 6 | 1 | 6 | 6 |
| -5 | 1 | -5 | 1 | 6 |
| 4 | 5 | 4 | 5 | 6 |
Answer: 6 (the subarray [4, -1, 2, 1], which started fresh at the 4).
The code
The reference solution is below, with comments on every important line.
How fast is it?
- Time: O(n). One pass.
- Memory: O(1). Two variables.
Common mistakes
- Starting
best(orcurrent) at0. On[-3, -1, -2]you'd return0, which isn't the sum of any non-empty subarray. Start withnums[0]. - Resetting
currentto0when it goes negative, then forgetting to compare.max(x, current + x)handles it in one line. - Returning
currentinstead ofbest. The best subarray might have ended earlier.
Going deeper
- Greedy or DP? Both.
currentis a one-variable DP ("best sum ending here", like Maximum Product Subarray), and "drop a negative prefix" is a greedy choice that the DP proves is safe. That's why it's often filed under Greedy. - To return the subarray itself, also remember where the current run started and where the best one ended.
Reference solution
/**
* @param {number[]} nums
* @return {number}
*/
export default function maxSubArray(nums) {
let current = nums[0] // best sum of a subarray ENDING at the current element
let best = nums[0] // best sum anywhere (not 0: every number may be negative)
for (let i = 1; i < nums.length; i++) {
// Start fresh at nums[i], or extend: extending only loses when current is negative.
current = Math.max(nums[i], current + nums[i])
best = Math.max(best, current)
}
return best
}export default function maxSubArray(nums: number[]): number {
let current = nums[0] // best sum of a subarray ENDING at the current element
let best = nums[0] // best sum anywhere (not 0: every number may be negative)
for (let i = 1; i < nums.length; i++) {
// Start fresh at nums[i], or extend: extending only loses when current is negative.
current = Math.max(nums[i], current + nums[i])
best = Math.max(best, current)
}
return best
}def max_sub_array(nums: list[int]) -> int:
# current: best sum of a subarray ENDING at the current element.
# best: best sum anywhere (not 0: every number may be negative).
current = best = nums[0]
for x in nums[1:]:
# Start fresh at x, or extend: extending only loses when current is negative.
current = max(x, current + x)
best = max(best, current)
return best