AlgoViz

Kadane's algorithm

medium 16 min

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

See it run

Walk the array once and at every element ask one question, extend the run or restart here, while the best run so far waits in mint.

Operations

Brute force: every subarray

Fix a start i, grow the end j to the right and keep a running sum. That checks all n(n + 1) / 2 subarrays in O(n²); re-adding each subarray from scratch would be O(n³).

Step 1 of 8

The question

nums

  1. -20
  2. 31
  3. -12
  4. 43
subarrays = 4 · 5 / 2 = 10

Array [-2, 3, -1, 4]. A subarray is a contiguous run, at least one element long. Which run has the largest sum? The obvious way: try them all and remember the best.

Step 1: The question

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, growing the run            total += nums[j]          # running sum: no inner re-summing            best = max(best, total)    return best# The O(n^3) version re-adds nums[i..j] for every pair:#     best = max(best, sum(nums[i:j + 1]))
Time
O(n²), or O(n³) with re-summing
Space
O(1)
n = 1,000
500,500 subarrays
Kadane
1,000 steps

Always mention the running-sum trick before Kadane: it turns O(n³) into O(n²) and shows the interviewer you see the repeated work.

In the real world

The same kadane's algorithm doing real jobs. Pick one and step through it.

The original four-element trace: restart once, extend twice, finish on 6.

Step 1 of 5

Start: cur = best = -2

nums

  1. -20i
  2. 31
  3. -12
  4. 43
cur = -2best = -2cur range = [0, 0]best range = [0, 0]

Both variables start at the first element, -2. The run so far is just index 0.

Step 1: Start: cur = best = -2

def max_subarray(nums):    cur = best = nums[0]              # a subarray holds at least one element    start = best_l = best_r = 0    for i in range(1, len(nums)):        if nums[i] > cur + nums[i]:   # true exactly when cur < 0            cur = nums[i]             # restart: the past only drags us down            start = i        else:            cur += nums[i]            # extend the current run        if cur > best:            best, best_l, best_r = cur, start, i    return best, best_l, best_r

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Starting cur and best at 0

    critical

    With best = 0 an all-negative array returns 0, the sum of an empty subarray. A subarray must contain at least one element, so start from nums[0] (or -inf).

    Wrong
    def max_subarray(nums):    cur = best = 0    for x in nums:        cur = max(x, cur + x)        best = max(best, cur)    return best                        # [-3, -1, -4] gives 0
    Right
    def max_subarray(nums):    cur = best = nums[0]    for x in nums[1:]:        cur = max(x, cur + x)        best = max(best, cur)    return best                        # [-3, -1, -4] gives -1
  • Returning cur instead of best

    critical

    cur is the best run ending at the last index. The best run overall may have ended earlier: on [-2, 1, -3, 4, -1, 2, 1, -5, 4] cur finishes at 5 while the answer is 6.

    Wrong
    for x in nums[1:]:    cur = max(x, cur + x)return cur                             # 5
    Right
    for x in nums[1:]:    cur = max(x, cur + x)    best = max(best, cur)return best                            # 6
  • Restarting whenever the element is negative

    major

    The rule looks at the running sum, not at the new element. On [4, -1, 2, 1] restarting at -1 returns 4 and loses the answer 6; 4 is enough credit to keep going.

    Wrong
    for x in nums[1:]:    cur = x if x < 0 else cur + x      # [4, -1, 2, 1] gives 4
    Right
    for x in nums[1:]:    cur = x if cur < 0 else cur + x    # same as max(x, cur + x): gives 6
  • Product: updating hi before computing lo

    major

    lo must use the old hi. After hi = max(x, hi * x, lo * x), the line lo = min(x, hi * x, lo * x) multiplies by the new hi, and [2, -5, -2, -4, 3] returns 480, a product no subarray has, instead of 24.

    Wrong
    for x in nums[1:]:    hi = max(x, hi * x, lo * x)    lo = min(x, hi * x, lo * x)        # uses the new hi
    Right
    for x in nums[1:]:    cands = (x, hi * x, lo * x)    hi, lo = max(cands), min(cands)    # both from the old values
  • Circular: forgetting the all-negative guard

    major

    When every number is negative, the minimum subarray is the whole array and total - best_min = 0, the empty run. [-3, -2, -3] would return 0 instead of -2.

    Wrong
    return max(best_max, total - best_min)     # [-3, -2, -3] gives 0
    Right
    if best_max < 0:    return best_max                         # -2return max(best_max, total - best_min)
  • Losing the start index

    minor

    When you need the subarray itself, record where the current run started at each restart, and copy start and i into the best range only when best improves. Setting best_l = i on a restart moves the answer's start even when best did not change.

    Wrong
    if nums[i] > cur + nums[i]:    cur = nums[i]    best_l = i                          # moves the best range too early
    Right
    if nums[i] > cur + nums[i]:    cur = nums[i]    start = i                           # only the current run moves...if cur > best:    best, best_l, best_r = cur, start, i

Interview tips

  • How to explain it

    • cur is the best sum of a subarray that ends at index i: that is dp[i].
    • dp[i] = max(nums[i], dp[i - 1] + nums[i]): restart here, or extend the best run ending at i - 1.
    • The answer is the largest dp[i], tracked in best as we go.
    • Only dp[i - 1] is read, so two variables: O(n) time, O(1) space.
  • Spot it in problems

    • Largest or smallest sum of a contiguous run, no fixed length.
    • Best buy and sell once: Kadane on the daily price changes.
    • Products: carry hi and lo. Circle: max(straight, total - min run).
    • Fixed window length: sliding window instead. Many range queries: prefix sums.
  • Memory tricks

    • E vs R, then M: Extend or Restart, then update the Max.
    • Debt is never worth carrying: a negative cur means restart.
    • Example to know cold: [-2, 1, -3, 4, -1, 2, 1, -5, 4] gives 6 from [4, -1, 2, 1].
  • Watch out

    • Start from nums[0], not 0, unless empty subarrays are allowed.
    • Return best, not cur.
    • Product: update hi and lo together. Circular: guard the all-negative case.