Kadane's algorithm
medium 16 minFind 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
- -20
- 31
- -12
- 43
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
- -20i
- 31
- -12
- 43
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_rCommon mistakes
The bugs interviewers watch for, with the fix beside each.
Starting cur and best at 0
criticalWith 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).
Wrongdef 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 0Rightdef 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 -1Returning cur instead of best
criticalcur 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.
Wrongfor x in nums[1:]: cur = max(x, cur + x)return cur # 5Rightfor x in nums[1:]: cur = max(x, cur + x) best = max(best, cur)return best # 6Restarting whenever the element is negative
majorThe 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.
Wrongfor x in nums[1:]: cur = x if x < 0 else cur + x # [4, -1, 2, 1] gives 4Rightfor x in nums[1:]: cur = x if cur < 0 else cur + x # same as max(x, cur + x): gives 6Product: updating hi before computing lo
majorlo 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.
Wrongfor x in nums[1:]: hi = max(x, hi * x, lo * x) lo = min(x, hi * x, lo * x) # uses the new hiRightfor x in nums[1:]: cands = (x, hi * x, lo * x) hi, lo = max(cands), min(cands) # both from the old valuesCircular: forgetting the all-negative guard
majorWhen 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.
Wrongreturn max(best_max, total - best_min) # [-3, -2, -3] gives 0Rightif best_max < 0: return best_max # -2return max(best_max, total - best_min)Losing the start index
minorWhen 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.
Wrongif nums[i] > cur + nums[i]: cur = nums[i] best_l = i # moves the best range too earlyRightif 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.