Maximum Subarray
Difficulty: Medium
You're given a list of numbers, which may include negatives. Find the contiguous subarray (no skipped elements) with the largest sum, and return that sum.
The subarray must contain at least one number.
Examples
Input: nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Output: 6
The subarray [4, -1, 2, 1] adds up to 6, which is the largest sum of any contiguous stretch.
Input: nums = [1]
Output: 1
The only subarray is [1] itself.
Input: nums = [5, 4, -1, 7, 8]
Output: 23
The whole array sums to 23, and no smaller stretch beats that.
Constraints
1 <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
Approach
Checking every subarray works but repeats a lot of summing.
Scan left to right with a running sum. If the sum ending at the previous position is negative, it can only hurt anything that continues past it. So throw that prefix away and start fresh from the current number.
This is Kadane's algorithm: one pass, a running sum that resets whenever its prefix goes negative, and the best running sum seen so far.
Solutions
Brute Force - Check Every Subarray
From every starting index, extend the subarray one element at a time and compare its sum to the best so far.
function maxSubArray(nums) {
let best = -Infinity;
for (let i = 0; i < nums.length; i++) {
let sum = 0;
for (let j = i; j < nums.length; j++) {
sum += nums[j];
best = Math.max(best, sum);
}
}
return best;
}Time: O(n^2) · Space: O(1)
Optimal - Kadane's Algorithm
Keep a running sum for the best subarray ending at the current position. When it turns negative, reset it to 0, since a negative prefix never helps a later sum.
function maxSubArray(nums) {
let best = nums[0];
let curr = 0;
for (const num of nums) {
if (curr < 0) curr = 0;
curr += num;
best = Math.max(best, curr);
}
return best;
}Time: O(n) · Space: O(1)