Kadane: Max Subarray
Read a little, play a little. No scary maths, and no rush.
The best days in a row
Given daily profit/loss numbers, find the contiguous stretch with the biggest total. Brute force checks every start/end pair — O(n²). But notice: the best subarray ending here either extends yesterday's streak or starts fresh today. One left-to-right pass decides, per element. That's Kadane's algorithm, and the "extend or restart" instinct behind it.
The five lines
def max_sub(a):
cur = best = a[0]
for x in a[1:]:
cur = max(x, cur + x) # restart here, or extend the streak?
best = max(best, cur) # remember the best streak ever seen
return best
Trace [-2, 1, -3, 4, -1, 2, 1, -5, 4]: the streak rebuilds from 4, grows through -1, 2, 1 to 6, and nothing later beats it. Answer: 6.
The trace, step by step
For [-2, 1, -3, 4, -1, 2, 1, -5, 4], tracking cur (best sum ending here) and best (best seen so far):
- −2: cur −2, best −2 (start)
- 1: restart beats extending (1 > −1), so cur 1, best 1
- −3: extend to −2, best 1
- 4: restart (4 > 2), so cur 4, best 4
- −1: extend to 3, best 4
- 2: extend to 5, best 5
- 1: extend to 6, best 6
- −5: extend to 1, best 6
- 4: extend to 5, best 6
Answer: 6, from the run [4, -1, 2, 1].
Why restarting is safe
Restarting happens exactly when cur + x < x, which means cur was negative. A negative running sum can only drag down any subarray that continues past it, so no future best subarray would ever want to include it. Dropping it loses nothing. That one-line argument is the proof interviewers hope to hear.
The two traps
- All negatives (
[-3, -1, -2]): the answer is-1, not 0 — initializingbest = 0fails this classic edge. Starting froma[0]handles it naturally. - "Return the subarray, not the sum": track start/end indices alongside
cur/best— same loop, two more variables.
Recovering the subarray itself
Keep a start index that moves to the current position whenever you restart. Whenever best improves, save (start, i) as the best range. For the example above, the restart at the value 4 sets start to index 3, and the best is recorded when index 6 is reached, giving the range 3 to 6. If several ranges tie for the best sum, decide up front whether to report the first one found or the shortest, and say which.
It is dynamic programming in disguise
cur is the answer to a smaller question: "what is the best subarray that ends exactly here?" Each answer is built from the previous one, which is the core idea of dynamic programming. Kadane simply notices that only the previous answer is ever needed, so it keeps one number instead of a whole table.
Where it leads
Maximum product subarray (track min and max, since negatives flip), circular arrays (total minus minimum), and stock-profit problems all rhyme with Kadane. Learn the decision — extend or restart — and the family follows.
Remember this
- Best-ending-here + global best, one pass, O(n) time O(1) space.
- All-negative input is the edge interviewers always test.
Check your understanding
5 questions · first-try answers earn the most XP
My notes
Saved in this browser. Highlight a line above and save it, or write it in your own words.
Nothing saved yet. Your highlights will live here.
References
Finished reading?
Ticking it here also ticks the chapter in the sidebar, the section count and your streak — it is all one number.
End of Core Patterns
Take the section checkpoint
A short mixed quiz on all 7 chapters, to check you are ready to move on.
Related chapters
Practice this pattern elsewhere
More problems to practise on external judges. Both links open the site home rather than a specific set, so you can pick problems for this pattern.
Spotted a mistake or want a topic covered? Report an issue