Maximum Subarray

mediumGreedy & Intervals28 stepsJava · Python · C++

Find the contiguous subarray with the largest sum. Walk once, keeping the best sum of a subarray ending here: either extend the previous one or start fresh at the current number, whichever is bigger.

▶ Watch the animated trace

Traced input: nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] → 6. Original problem: neetcode.io/problems/maximum-subarray

Complexity

BestO(n)
AverageO(n)
WorstO(n)
SpaceO(1)

One pass, two variables.

Key idea

Common mistakes

Solution

Java
int maxSubArray(int[] nums) {
    int cur = nums[0], best = nums[0];
    for (int i = 1; i < nums.length; i++) {
        cur = Math.max(nums[i], cur + nums[i]);
        best = Math.max(best, cur);
    }
    return best;
}
Python
def maxSubArray(nums: List[int]) -> int:
    cur = best = nums[0]
    for x in nums[1:]:
        cur = max(x, cur + x)
        best = max(best, cur)
    return best
C++
int maxSubArray(vector<int>& nums) {
    int cur = nums[0], best = nums[0];
    for (size_t i = 1; i < nums.size(); i++) {
        cur = max(nums[i], cur + nums[i]);
        best = max(best, cur);
    }
    return best;
}

Edge cases

Each one has its own trace in the interactive view.

CaseInputAnswer
All negative
The best subarray is the single largest element.
nums = [-3, -1, -2]-1
Single element
Just itself.
nums = [5]5
All positive
The whole array.
nums = [1, 2, 3]6
Zero in the middle
Extending through the -1 still pays off.
nums = [2, 0, -1, 3]4
← Best Time to Buy and Sell Stock with CooldownJump Game →