Maximum Subarray
Medium
Topics
Given an integer array nums, find the contiguous subarray with the largest sum and return its sum.
Example 1
The braced run is the contiguous block with the largest sum, 6. The one-pass rule is the whole idea: a running sum that has gone negative can never help what comes next, so drop it and start again at the current element.
Cells are the array values; the small numbers underneath are indices.
Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: [4,-1,2,1] has sum 6.
Example 2
Input: nums = [5,4,-1,7,8] Output: 23
Constraints
- 1 <= nums.length <= 10^5
- -10^4 <= nums[i] <= 10^4
Editorial — intuition, approach, complexity and pitfalls
Intuition
Consider the best subarray that ends at each index. When you extend to a new element, you either continue the previous subarray or start fresh at the new element.
The decision is simple: if the running sum has dropped below zero, it can only hurt what follows, so discard it and restart. This is Kadane’s algorithm.
Approach
- Keep
cur= best sum of a subarray ending here, andbest= best anywhere. - For each element:
cur = max(x, cur + x)(restart vs. extend). - Update
best = max(best, cur). - Return
best.
Walkthrough
nums = [-2, 1, -3, 4, -1, 2, 1]
x=-2 cur=-2 best=-2
x= 1 cur=1 best=1
x=-3 cur=-2 best=1
x= 4 cur=4 best=4
x=-1 cur=3 best=4
x= 2 cur=5 best=5
x= 1 cur=6 best=6 -> answer 6Complexity
- Time — O(n): one pass, constant work per element.
- Space — O(1): two running scalars.
Common Pitfalls
- Initialize with
nums[0], not 0 — an all-negative array must still return its largest single element.
Full Solution — all languages
class Solution:
def maxSubArray(self, nums):
best = nums[0]
running = nums[0]
# range, not nums[1:]: the slice would copy n-1 elements and quietly make
# this O(n) auxiliary space, which is the one property Kadane's is known for.
for i in range(1, len(nums)):
v = nums[i]
running = max(v, running + v)
best = max(best, running)
return bestimport java.util.*;
class Solution {
public int maxSubArray(int[] nums) {
int best = nums[0], running = nums[0];
for (int i = 1; i < nums.length; i++) {
running = Math.max(nums[i], running + nums[i]);
best = Math.max(best, running);
}
return best;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int maxSubArray(vector<int>& nums) {
int best = nums[0], running = nums[0];
for (size_t i = 1; i < nums.size(); i++) {
running = max(nums[i], running + nums[i]);
best = max(best, running);
}
return best;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var maxSubArray = function(nums) {
let best = nums[0], running = nums[0];
for (let i = 1; i < nums.length; i++) {
running = Math.max(nums[i], running + nums[i]);
best = Math.max(best, running);
}
return best;
};