Maximum Subarray
Medium · Greedy
Jump to codeFind the greatest sum of a nonempty contiguous subarray within a nonempty integer array.
Examples
Example 1
nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Example 2
nums = [1]
Output: 1
Constraints
- 1 <= nums.length <= 1000
- -1000 <= nums[i] <= 1000
Need a hint?
A negative running prefix can only hurt the next segment.
Asked in real interviews
Candidates reported versions of Maximum Subarray from these company interviews. Some company questions are locked and open with Premium or XP.
- Find the Maximum-Sum Contiguous SubarrayJ.P. Morgan
- Maximum Subarray Sum of an Array Repeated K TimesMicrosoft
Solution approach
Track the best sum ending at the current position. Either start over at x or extend the previous segment with x, whichever is larger. Update a global best after each step. Initialize from the first element to handle all-negative arrays.
Complexity
O(n) time and O(1) extra space.
Python reference solution
def maxSubArray(nums):
ending = best = nums[0]
for value in nums[1:]:
ending = max(value, ending + value)
best = max(best, ending)
return best
JavaScript solution
function maxSubArray(nums) {
let ending = nums[0], best = nums[0];
for (let i = 1; i < nums.length; i++) {
ending = Math.max(nums[i], ending + nums[i]);
best = Math.max(best, ending);
}
return best;
}
Java solution
import java.util.*;
class Solution {
public int maxSubArray(int[] nums) {
int ending = nums[0], best = nums[0];
for (int i = 1; i < nums.length; i++) {
ending = Math.max(nums[i], ending + nums[i]);
best = Math.max(best, ending);
}
return best;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maxSubArray(vector<int> &nums) {
int ending = nums[0], best = nums[0];
for (size_t i = 1; i < nums.size(); i++) {
ending = max(nums[i], ending + nums[i]);
best = max(best, ending);
}
return best;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 8 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
-2,
1,
-3,
4,
-1,
2,
1,
-5,
4
]
]6
[
[
1
]
]1
[
[
5,
4,
-1,
7,
8
]
]23
[
[
-3,
-2,
-5
]
]-2
[
[
0,
0,
0
]
]0
Drafts are saved per language in this browser when storage is available.