The problem. You are given an integer array nums. Find the contiguous subarray (containing at least one number) with the largest sum, and return that sum.
Input: nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Output: 6
Why: the slice [4, -1, 2, 1] adds up to 6, and no other slice does better.A subarray is a run of neighbouring elements. [4, -1, 2] is a subarray of the example; [4, 2] is not, because it skips the -1 in between.
If every number were positive, the answer would simply be the whole array. The negative numbers are what make this interesting: sometimes a -1 inside a run is worth keeping because the numbers after it pay it back, and sometimes a long negative stretch means you should give up and start again.
[-3, -1, -2] the answer is -1, not 0.A subarray is fixed by its start i and end j. Try every pair, add up nums[i..j] with a third loop, and keep the biggest total.
function maxSubArray(nums) { let maxSum = -Infinity; for (let i = 0; i < nums.length; i++) { for (let j = i; j < nums.length; j++) { let sum = 0; for (let k = i; k <= j; k++) sum += nums[k]; // nums[i..j], from scratch maxSum = Math.max(maxSum, sum); } } return maxSum;}Time O(n³), space O(1). The sum of nums[i..j] is just the sum of nums[i..j-1] plus nums[j] — yet we add it all up again for every j.
Fix the start i, then stretch the end j one step at a time, adding nums[j] to a running sum. Every (i, j) pair still gets checked, but each costs one addition instead of a whole loop.
function maxSubArray(nums) { let maxSum = -Infinity; for (let i = 0; i < nums.length; i++) { let currSum = 0; for (let j = i; j < nums.length; j++) { currSum += nums[j]; // sum of nums[i..j] maxSum = Math.max(maxSum, currSum); } } return maxSum;}Time O(n²), space O(1). Much better — but for 100,000 numbers that's still around five billion additions. We're still trying every starting point.
Walk the array once, and at every index ask a single question: what is the best subarray that ends exactly here?
There are only two options. Either the best run ending here extends the best run that ended one step earlier, or it starts fresh at this element. And the choice is easy: if the run behind you has a negative sum, it can only drag down whatever comes next — so drop it and restart.
currSum = max(nums[i], currSum + nums[i]) // restart here, or extend
maxSum = max(maxSum, currSum) // remember the best run seenThat is the whole of Kadane's algorithm. Here it is on [-2, 3, -1, 2] — the green cells are the run that currSum describes:
currSum and maxSum to nums[0] — a one-element subarray is always valid.i, set currSum = max(nums[i], currSum + nums[i]): extend the current run or restart at i.maxSum = max(maxSum, currSum) so the best run seen so far is never forgotten.maxSum is the answer.Step through the classic example, then try your own input. An all-negative array shows why we start from nums[0] instead of 0.
Time O(n), space O(1). Each element is looked at once, and only two numbers are kept.
O(n³)About n²/2 subarrays, each re-added from scratch in O(n).
O(1)Only loop indexes and a sum.
[5] returns 5.[-3, -1, -2] returns -1, the single largest element.[0, -1, 0] returns 0."What is the best answer that ends here?" is a tiny piece of dynamic programming, and it unlocks a family of problems: the maximum product subarray (track the smallest product too, because two negatives make a positive), the maximum circular subarray, and the best time to buy and sell a stock, which is Kadane's algorithm applied to day-to-day price changes.
O(n²)Still tries every start, but each extension costs only O(1).
O(1)One running sum per start.
O(n)Each element is looked at once: extend the run or restart.
O(1)Only two numbers: the current run and the best.