Kadane and subarray sums
Walk the array once, keeping the best answer for a subarray that ends exactly here. Each new element either extends that run or starts a fresh one, whichever is better. The overall answer is the best of those.
How to recognise it
- The largest (or smallest) sum of a contiguous subarray.
- Values can be negative, so a sliding window cannot decide when to shrink.
- The answer for a run ending at i depends only on the run ending at i - 1.
- A product instead of a sum, where a negative number can flip the smallest into the largest.
The idea in one picture
You walk along a road of numbers carrying a bag that holds the sum of the stretch you are on. At each step you ask one question: is my bag helping? If the bag's total is negative, it can only drag the next number down, so you empty it and start a fresh stretch here. Otherwise you add the new number. You write down the best total your bag ever held. That is Kadane's algorithm: one pass, two numbers.
Template
current = nums[0] # best sum of a subarray ending here
best = nums[0]
for i from 1 to n - 1:
current = max(nums[i], current + nums[i])
best = max(best, current)
return best
Why it is correct
Every subarray ends somewhere. For a fixed end i, the best subarray ending there is either nums[i] alone or
nums[i] added to the best subarray ending at i - 1. Nothing else can be better, because any other choice for the
earlier part has a smaller sum. So current is exactly right at every step, and best takes the best over all ends.
A guided example: [-2, 1, -3, 4, -1, 2, 1, -5, 4]
| i | value | current | best |
|---|---|---|---|
| 0 | -2 | -2 | -2 |
| 1 | 1 | 1 (start fresh) | 1 |
| 2 | -3 | -2 | 1 |
| 3 | 4 | 4 (start fresh) | 4 |
| 4 | -1 | 3 | 4 |
| 5 | 2 | 5 | 5 |
| 6 | 1 | 6 | 6 |
| 7 | -5 | 1 | 6 |
| 8 | 4 | 5 | 6 |
Variations
- Smallest sum: swap
maxforminin both lines. - Product: keep both the largest and the smallest product ending here, and swap them when the new value is negative.
- Which subarray: remember where the current run started, and copy it into the answer whenever
bestimproves.
Common mistakes
- Starting
currentandbestat 0, which returns 0 for an all-negative array that has no empty subarray. - Returning
currentat the end instead ofbest.currentis only the best run ending at the last element. - Using a sliding window. With negative values a window cannot tell when to shrink.
Problems
- Maximum Subarraymediumguide ready
- Maximum Product Subarraymediumguide ready
- Smallest sum contiguous subarraymediumguide ready