AlgoViz

Kadane's algorithm

medium 16 min

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

Remember it

The few things worth knowing cold, and how to make them stick.

Memory hook

Extend or Restart, then keep the Max: debt is never worth carrying.

Walking a money trail where every stop pays or costs you. You carry your running total; the moment it turns into debt you drop it and start again at the next stop, while a note in your pocket remembers the best stretch so far.

Cheat sheet

Update
cur = max(x, cur + x)
Answer
best = max(best, cur)
Meaning of cur
best run ending at i, dp[i]
Restart when
cur < 0
Initialise
cur = best = nums[0]
Kadane
O(n) time, O(1) space
Brute force
O(n²) running sum, O(n³) re-summing
Product
carry hi and lo
Circular
max(maxRun, total - minRun)

Spot it when you see

  • Largest or smallest sum of a contiguous run with no fixed length.
  • Best single buy-then-sell from a price list.
  • Largest product of a contiguous run.
  • A best run on a circular array.
  • The best streak in a series of gains and losses.

Tricks that stick

  • E vs R, then M: Extend (cur + x) versus Restart (x), then update the Max.
  • Debt rule: a negative running total only drags you down, so drop it.
  • The classic array to know cold: [-2, 1, -3, 4, -1, 2, 1, -5, 4] gives 6 from [4, -1, 2, 1].
  • Products flip: the smallest product can become the largest, so carry both.
  • Circle: total minus the worst middle.

Do not forget

  • Starting best at 0, so all-negative input returns 0.
  • Returning cur instead of best.
  • Restarting because the element is negative rather than because cur is negative.
  • Updating hi before using the old hi to compute lo in the product version.
  • Forgetting the all-negative guard in the circular version.
  • Using Kadane for a fixed window length, which needs a sliding window.