AlgoViz

Kadane's algorithm

medium 16 min

Find the contiguous subarray with the largest sum in one pass.

Video lesson · Chapter 1 of 8

The night market ledger

0:00 / 5:46

Kadane's algorithm in 75 seconds

1:26Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

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.

Index012345678
nums-21-34-121-54
In the best runyesyesyesyes
The best run keeps the -1 because the 4 before it pays for it and the 2 and 1 after it pay it back.
  • 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 P[j+1]−P[i]P[j+1] - P[i] with running totals PP. 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 n(n+1)2\frac{n(n+1)}{2} subarrays, one per (start, end) pair. Summing each one from scratch costs up to nn more steps, giving O(n3)O(n^3). Keeping a running total while the end moves right makes each new subarray cost one addition, giving O(n2)O(n^2).

Python
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]))   # 6
The O(n²) brute force with a running sum. The commented line is the O(n³) version.
Edit and run it in your browser

How much work each version does

∑i=0n−1∑j=in−1(j−i+1)⏟re-summing=n(n+1)(n+2)6=Θ(n3)∑i=0n−1(n−i)⏟running sum=n(n+1)2=Θ(n2)\underbrace{\sum_{i=0}^{n-1}\sum_{j=i}^{n-1}(j-i+1)}_{\text{re-summing}} = \frac{n(n+1)(n+2)}{6} = \Theta(n^3) \qquad \underbrace{\sum_{i=0}^{n-1}(n-i)}_{\text{running sum}} = \frac{n(n+1)}{2} = \Theta(n^2)
For n=105n = 10^5 the running-sum version still needs about 5×1095 \times 10^9 additions. Kadane needs 10510^5.

The decision

Extend the run or restart here

  • EXTEND

    Take cur + nums[i]: the run so far is helping, because cur is not negative. Keep the momentum.

  • RESTART

    Take nums[i] alone: cur is 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, so best remembers it.

One step of Kadane's algorithm

Comparing 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

nums[i]>cur+nums[i]  ⟺  cur<0\text{nums}[i] > \text{cur} + \text{nums}[i] \iff \text{cur} < 0
So the rule never looks at whether the new element is negative. A -1 after a run worth 4 is simply absorbed.

As DP

dp[i] = max(a[i], dp[i-1] + a[i])

Best sum of a subarray that ends exactly at i

dp[i]={a0i=0max⁡(ai, dp[i−1]+ai)i≥1answer=max⁡0≤i<ndp[i]dp[i] = \begin{cases} a_0 & i = 0 \\ \max\big(a_i,\ dp[i-1] + a_i\big) & i \ge 1 \end{cases} \qquad \text{answer} = \max_{0 \le i < n} dp[i]
The variable cur is dp[i]dp[i] 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 ii. Either it is just aia_i, or it is longer, and then its part ending at i−1i - 1 must itself be the best run ending at i−1i - 1 (if a better one existed, swapping it in would beat our best). So the best is aia_i or dp[i−1]+aidp[i-1] + a_i, whichever is larger: optimal substructure with one choice per cell. Every subarray ends somewhere, so the overall answer is the largest dp[i]dp[i].

i012345678
a[i]-21-34-121-54
dp[i]-21-2435615
choicestartrestartextendrestartextendextendextendextendextend
The answer is the maximum of the dp row, 6 at i=6i = 6, not the last cell, 5.

Walkthrough

Trace [-2, 1, -3, 4, -1, 2, 1, -5, 4]

inums[i]max(nums[i], cur + nums[i])curbestDecision
0-2start-2-2init
11max(1, -1)11restart
2-3max(-3, -2)-21extend
34max(4, 2)44restart
4-1max(-1, 3)34extend
52max(2, 5)55extend
61max(1, 6)66extend
7-5max(-5, 1)16extend
84max(4, 5)56extend
Bold marks a new best. Two restarts, both right after cur went negative.
Python
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]))                   # 15
Kadane's algorithm: two variables and one loop.
Edit and run it in your browser

Edge 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

Two ranges live side by side: the current run (start to i) and the best run (best_l to best_r).
Python
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]
Kadane that also returns where the best run is.
Edit and run it in your browser

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 ii.

The hi and lo recurrences

hii=max⁡(xi, hii−1⋅xi, loi−1⋅xi)loi=min⁡(xi, hii−1⋅xi, loi−1⋅xi)answer=max⁡ihii\begin{aligned} hi_i &= \max\big(x_i,\ hi_{i-1} \cdot x_i,\ lo_{i-1} \cdot x_i\big) \\ lo_i &= \min\big(x_i,\ hi_{i-1} \cdot x_i,\ lo_{i-1} \cdot x_i\big) \end{aligned} \qquad \text{answer} = \max_i hi_i
Both use the previous values. A zero makes both products 0, so the next element effectively restarts: zeros split the array into independent pieces.

Where the new extremes come from

When x is negative, the old lo produces the new hi and the old hi produces the new lo.
Python
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]))          # 0
Maximum product subarray in one pass.
Edit and run it in your browser

Variant

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

answer={maxRunif maxRun<0max⁡(maxRun, total−minRun)otherwise\text{answer} = \begin{cases} \text{maxRun} & \text{if } \text{maxRun} < 0 \\ \max\big(\text{maxRun},\ \text{total} - \text{minRun}\big) & \text{otherwise} \end{cases}
On [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

When every number is negative, minRun is the whole array and total - minRun = 0 would be the empty run, so the guard returns maxRun.
Python
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]))            # -2
Circular maximum subarray with both passes in one loop.
Edit and run it in your browser

Comparison

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

max⁡i≤j(P[j+1]−P[i])=max⁡j(P[j+1]−min⁡i≤jP[i])\max_{i \le j} \big(P[j+1] - P[i]\big) = \max_{j} \Big(P[j+1] - \min_{i \le j} P[i]\Big)
Keep the smallest prefix seen so far and subtract it from the current one. This is Kadane in disguise, and exactly the best-time-to-buy-and-sell-stock solution.
ApproachTimeSpaceNotes
Re-sum every subarrayO(n3)O(n^3)O(1)O(1)Three nested loops
Running sum per startO(n2)O(n^2)O(1)O(1)Fine for nn in the low thousands
Divide and conquerO(nlog⁡n)O(n \log n)O(log⁡n)O(\log n)Best crossing the middle plus each half
KadaneO(n)O(n)O(1)O(1)One pass, two variables
Product / circularO(n)O(n)O(1)O(1)hi and lo; or max and min runs

Picking the right tool for a subarray question

Most best-run-of-any-length questions end at one of the three Kadane leaves.

Recap

Key takeaways

Key points

  • cur is the best sum of a subarray ending at i: dp[i]=max⁡(ai, dp[i−1]+ai)dp[i] = \max(a_i,\ dp[i-1] + a_i).
  • Restart exactly when cur is negative; a negative element on its own never forces a restart.
  • Return best, the maximum over all i, not the last cur.
  • Start from nums[0] so an all-negative array returns its largest element, not 0.
  • Track start on each restart and copy it into the best range only when best improves.
  • 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.

Sources