Kadane's algorithm
medium 16 minFind the contiguous subarray with the largest sum in one pass.
Video lesson · Chapter 1 of 8
The night market ledger
Kadane's algorithm in 75 seconds
1:26Reel
How it works
Step through the idea, or press Play.
Extend or restart. cur = max(nums[i], cur + nums[i]): keep the run going unless what you carry is negative
Understand it
Start here
The problem: the best contiguous run
Given an integer array nums, find the contiguous subarray (at least one element) with the largest sum. For [-2, 1, -3, 4, -1, 2, 1, -5, 4] the answer is 6, from [4, -1, 2, 1]. Contiguous matters: you cannot skip the -1 in the middle, which is what makes this harder than adding up the positives.
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|---|
| nums | -2 | 1 | -3 | 4 | -1 | 2 | 1 | -5 | 4 |
| In the best run | yes | yes | yes | yes |
Recap: DP in one line
A dynamic programming solution names a state, writes it in terms of smaller states, and fills them in order. If that is new, read Dynamic programming: the core idea first.
Recap: prefix sums
The sum of
nums[i..j]is with running totals . Kadane can be read as a clever pass over these totals; see Prefix sums.
Brute force
Try every subarray: O(n³), then O(n²)
There are subarrays, one per (start, end) pair. Summing each one from scratch costs up to more steps, giving . Keeping a running total while the end moves right makes each new subarray cost one addition, giving .
def max_subarray_brute(nums): n = len(nums) best = nums[0] for i in range(n): # every start total = 0 for j in range(i, n): # every end total += nums[j] # O(n^2): reuse the last sum # total = sum(nums[i:j + 1]) # O(n^3): re-add everything best = max(best, total) return bestprint(max_subarray_brute([-2, 1, -3, 4, -1, 2, 1, -5, 4])) # 6How much work each version does
The decision
Extend the run or restart here
EXTEND
Take
cur + nums[i]: the run so far is helping, becausecuris not negative. Keep the momentum.RESTART
Take
nums[i]alone:curis negative, so anything that carries it starts lower. Abandon the past.Track the MAX
After each step,
best = max(best, cur). The best run may have ended long ago, sobestremembers it.
One step of Kadane's algorithm
nums[i] with cur + nums[i] is the same test as asking whether cur is negative.Why the test is just the sign of cur
As DP
dp[i] = max(a[i], dp[i-1] + a[i])
Best sum of a subarray that ends exactly at i
cur is and best is the running maximum of the table. Each cell reads only the one before it, so the table collapses to one variable.Why it is right. Take the best subarray that ends at . Either it is just , or it is longer, and then its part ending at must itself be the best run ending at (if a better one existed, swapping it in would beat our best). So the best is or , whichever is larger: optimal substructure with one choice per cell. Every subarray ends somewhere, so the overall answer is the largest .
| i | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|---|
| a[i] | -2 | 1 | -3 | 4 | -1 | 2 | 1 | -5 | 4 |
| dp[i] | -2 | 1 | -2 | 4 | 3 | 5 | 6 | 1 | 5 |
| choice | start | restart | extend | restart | extend | extend | extend | extend | extend |
Walkthrough
Trace [-2, 1, -3, 4, -1, 2, 1, -5, 4]
| i | nums[i] | max(nums[i], cur + nums[i]) | cur | best | Decision |
|---|---|---|---|---|---|
| 0 | -2 | start | -2 | -2 | init |
| 1 | 1 | max(1, -1) | 1 | 1 | restart |
| 2 | -3 | max(-3, -2) | -2 | 1 | extend |
| 3 | 4 | max(4, 2) | 4 | 4 | restart |
| 4 | -1 | max(-1, 3) | 3 | 4 | extend |
| 5 | 2 | max(2, 5) | 5 | 5 | extend |
| 6 | 1 | max(1, 6) | 6 | 6 | extend |
| 7 | -5 | max(-5, 1) | 1 | 6 | extend |
| 8 | 4 | max(4, 5) | 5 | 6 | extend |
cur went negative.def max_subarray(nums): cur = best = nums[0] for x in nums[1:]: cur = max(x, cur + x) # extend or restart best = max(best, cur) # remember the best run so far return bestprint(max_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4])) # 6print(max_subarray([-2, 3, -1, 4])) # 6print(max_subarray([1, 2, 3, 4, 5])) # 15Edge case
All-negative arrays
On [-3, -1, -4, -2, -5] every run of two or more is smaller than its largest member, so the answer is the largest single element, -1. Kadane handles this on its own: cur is negative at every step, so it restarts every time and best ends up as the maximum.
Start from nums[0]
cur = best = nums[0], loop from index 1- All negatives give the largest element
- Matches the rule: at least one element
Start from 0
cur = best = 0, loop from index 0[-3, -1, -4]returns 0- 0 is the sum of the empty subarray, which is not allowed
Indices
Tracking where the best run starts and ends
To return the subarray, keep start, the index where the current run began. On a restart set start = i. When cur beats best, copy the current run's range into best_l, best_r = start, i. The best range only changes when best changes.
Which index moves when
def max_subarray_range(nums): cur = best = nums[0] start = best_l = best_r = 0 for i in range(1, len(nums)): if cur < 0: cur, start = nums[i], i # restart here else: cur += nums[i] # extend if cur > best: best, best_l, best_r = cur, start, i return best, best_l, best_rnums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]best, l, r = max_subarray_range(nums)print(best, nums[l:r + 1]) # 6 [4, -1, 2, 1]Variant
Maximum product subarray: carry min and max
Swap sums for products and one variable breaks: a very negative product becomes very positive after one more negative factor. On [2, -5, -2, -4, 3], the run [2, -5] has product -10, the worst so far, and one step later [2, -5, -2] is worth 20. So keep both extremes for runs ending at .
The hi and lo recurrences
Where the new extremes come from
def max_product(nums): hi = lo = best = nums[0] for x in nums[1:]: cands = (x, hi * x, lo * x) hi, lo = max(cands), min(cands) # both from the old values best = max(best, hi) return bestprint(max_product([2, -5, -2, -4, 3])) # 24 from [-2, -4, 3]print(max_product([2, 3, -2, 4])) # 6print(max_product([-2, 0, -1])) # 0Variant
Circular maximum subarray
If the last element is next to the first, a run can wrap past the end. A wrapping run takes both ends and skips one middle block, so it is largest when the skipped block has the smallest sum. Run Kadane twice, once with max and once with min.
Two cases cover every circular run
[5, -3, -2, 6, -1, 4]: maxRun = 9, total = 9, minRun = -5 for [-3, -2], so the wrap is 14 from [6, -1, 4, 5].Choosing the circular answer
def max_circular(nums): total = sum(nums) cur_max = best_max = nums[0] cur_min = best_min = nums[0] for x in nums[1:]: cur_max = max(x, cur_max + x) best_max = max(best_max, cur_max) cur_min = min(x, cur_min + x) best_min = min(best_min, cur_min) if best_max < 0: return best_max return max(best_max, total - best_min)print(max_circular([5, -3, -2, 6, -1, 4])) # 14print(max_circular([5, -3, 5])) # 10print(max_circular([-3, -2, -3])) # -2Comparison
When to use Kadane, and when not
Use Kadane when
- You want the maximum or minimum sum of a contiguous run of any length
- Maximum product subarray (with the hi and lo pair)
- Circular subarray problems
- Best single buy and sell: Kadane on the daily price changes
Reach for something else when
- The run has a fixed length k: sliding window
- You need many range-sum queries: prefix sums
- The elements need not be contiguous: that is a subsequence problem, often just add the positives
The same answer through prefix sums
| Approach | Time | Space | Notes |
|---|---|---|---|
| Re-sum every subarray | Three nested loops | ||
| Running sum per start | Fine for in the low thousands | ||
| Divide and conquer | Best crossing the middle plus each half | ||
| Kadane | One pass, two variables | ||
| Product / circular | hi and lo; or max and min runs |
Picking the right tool for a subarray question
Recap
Key takeaways
Key points
curis the best sum of a subarray ending at i: .- Restart exactly when
curis negative; a negative element on its own never forces a restart. - Return
best, the maximum over all i, not the lastcur. - Start from
nums[0]so an all-negative array returns its largest element, not 0. - Track
starton each restart and copy it into the best range only whenbestimproves. - Products need both hi and lo; circles need total minus the minimum run, with an all-negative guard.
- O(n) time, O(1) space, against O(n²) or O(n³) for brute force.