Technique
Kadane's Algorithm
best_ending_here = max(x, best_ending_here + x); the answer is the max over all positions.
Learn first1D / Fibonacci-style
0%
mastery
0/8 solved
0/8 solved
Recognise it
The signal
maximum (or minimum) sum contiguous subarray
1Brute force
All O(n2) subarrays.
2The observation
Recomputing sums: a negative running prefix is never worth keeping.
3Why it works
cur equals the best sum of a subarray ending at the current index.
Reach for it when
- +circular max subarray (total - min subarray)
- +max product subarray (track min too)
Not when
- ×length constraints (prefix-sum + mono-deque or ordered-set)
- ×need count of subarrays rather than max
Practice
0/8 solved
- Maximum Subarray SumCSESEasy
- Just Eat It!Codeforces1300
- Yarik and ArrayCodeforces1100
- Best Time to Buy and Sell StockAmazon, MetaEasy
- Maximum Product SubarrayAmazon, AdobeMedium
- Maximum SubarrayAmazon, MicrosoftMedium
- Maximum Sum on Even PositionsCodeforces1600
- Yet Another Yet Another TaskCodeforces2000
Pitfalls
Misconceptions
- !all-negative arrays (do not initialise answer to 0)