awelgorithms

Kadane is 1D DP

Updated

Kadane is dp[i] = max(a[i], dp[i-1]+a[i]) — best sum ending at i — plus a running global max. That is 1D DP on prefixes, not a sliding window of fixed width.

What to focus on

Restart when dp[i-1] is negative: a[i] alone beats extend. All-negative: the global is the largest element.

Worked examples

trace endings

a = [4, -1, 9, -1]
  1. i=0 ending 4, global 4
  2. i=1 max(-1, 4-1)=3, global 4
  3. i=2 max(9, 3+9)=12, global 12
  4. i=3 max(-1, 12-1)=11, global 12

Result: max 12

restart vs extend

a = [4, -1, 9, -1]
  1. after 3, 9 restarts would be 9 but 3+9=12 extends
  2. after 12, -1 extends to 11

Result: extend at 9

one cell

a = [4]
  1. ending 4
  2. global 4

Result: 4

Try it

Write kadane(a). a is an array of integers. dp[i] is the best sum ending at i. Track ending and global. Return the global max. A non-empty subarray exists. [4, -1, 9, -1] → max 12, extend at i=2. [4] → 4.

a is a non-empty array of integers. n ≥ 1. A non-empty subarray exists.