Sub topic 2
One Array, Updated in Place: Why Loop Direction Matters
This chapter assumes you can write bottom-up DP tables, know 0/1 knapsack and edit distance, and can read the dependency pattern of a recurrence. That pattern is the set of earlier cells each transition reads.
Loop Direction in a Single Array
Two-row knapsack keeps prev and curr as separate arrays. A single array can hold both, as long as each read finds the right version of the cell. In 0/1 knapsack, dp[c - w] must still hold the value from before the current item was considered. Looping capacity downward guarantees that, because smaller indices are overwritten later.
def knapsack_01(weights, values, capacity):
dp = [0] * (capacity + 1)
for w, v in zip(weights, values):
for c in range(capacity, w - 1, -1):
dp[c] = max(dp[c], dp[c - w] + v)
return dp[capacity]
def coin_change_ways(coins, amount):
dp = [0] * (amount + 1)
dp[0] = 1
for coin in coins:
for a in range(coin, amount + 1):
dp[a] += dp[a - coin]
return dp[amount]
print(knapsack_01([1, 3, 4], [15, 20, 30], 4)) # 35
print(coin_change_ways([1, 2, 5], 5)) # 4Coin change allows unlimited reuse of each coin, so it loops upward on purpose. That way dp[a - coin] already includes the current coin.
Keeping the Diagonal
Edit distance reads three cells: left, up, and the up-left diagonal. In a single row, the diagonal cell dp[i-1][j-1] has already been overwritten by the time you need it, so you save it in a variable first.
def edit_distance(s, t):
n = len(t)
dp = list(range(n + 1))
for i in range(1, len(s) + 1):
diag = dp[0]
dp[0] = i
for j in range(1, n + 1):
temp = dp[j]
if s[i - 1] == t[j - 1]:
dp[j] = diag
else:
dp[j] = 1 + min(diag, dp[j], dp[j - 1])
diag = temp
return dp[n]
print(edit_distance("kitten", "sitting")) # 3Modulo Indexing for the Last k Layers
If a recurrence looks back k steps, a buffer of size k is enough. Index it with i % k, so each new value overwrites the oldest one.
def tribonacci(n):
t = [0, 1, 1]
if n < 3:
return t[n]
for i in range(3, n + 1):
t[i % 3] = t[0] + t[1] + t[2]
return t[n % 3]
print(tribonacci(10)) # 149Removing Derivable Dimensions
If one state component can be computed from the others, drop it. In job assignment over a bitmask of taken jobs, the next worker's index equals the number of set bits in the mask. So dp[i][mask] becomes dp[mask], and the table shrinks from n·2ⁿ entries to 2ⁿ.
Collapsing into a State Machine
Some problems only need a few labeled states per step. Stock trading with a one-day cooldown has three: holding a share, just sold, and resting. All three are updated together each day, so the whole table fits in three variables.
def max_profit_cooldown(prices):
hold, sold, rest = float('-inf'), 0, 0
for p in prices:
hold, sold, rest = max(hold, rest - p), hold + p, max(rest, sold)
return max(sold, rest)
print(max_profit_cooldown([1, 2, 3, 0, 2])) # 3Exercise
Run knapsack_01 with the capacity loop going upward, using weights [2], values [3], and capacity 4. What does it return, and why is that wrong?
Show answer
It returns 6. dp[2] becomes 3, and then dp[4] = dp[2] + 3 = 6, so the single item is used twice. That is unbounded behavior. The correct 0/1 answer is 3.
Exercise
In edit_distance, why must diag be set to temp, rather than to dp[j], at the end of each inner step?
Show answer
At that point dp[j] already holds the new row's value. temp holds the old value dp[i-1][j], and that value becomes the diagonal for column j+1.