awelgorithms

Rolling arrays save a DP dimension

Updated

If dp[i] only reads dp[i-1] (and maybe dp[i-2]), keep those rows/scalars and drop the i axis. Knapsack 0/1 can keep one W-array if you scan w from high to low. The saved dimension is gone from memory, not from the math.

What to focus on

Rolling does not change the recurrence. It changes what you still have in RAM. Scanning w low-to-high on 0/1 reuses the new value of the same item — that is unbounded by accident.

Worked examples

robber two scalars

a = [4, 1, 9]
  1. prev2=4, prev1=4
  2. cur=max(4, 4+9)=13

Result: O(1) extra

knapsack one row

a = [1, 4, 9], W = 5
  1. scan w=5..1 after item 1
  2. then item 4, then item 9

Result: O(W) extra

Kadane two ints

a = [4, -1, 9, -1]
  1. ending and global only
  2. no n-array required

Result: O(1) extra

Try it

Write roll(a). a is an array of integers. W and item weights are positive. dp[i] only reads dp[i-1] and maybe dp[i-2]. Keep those scalars or one W-row. Return the same answer with less extra space. [4, 1, 9] robber → two ints, 13. [1, 4, 9] W=5 → one row high-to-low. Kadane [4, -1, 9, -1] → two ints.

a is a non-empty array of integers, n ≥ 3. W and item weights are positive.