Sub topic 5
One Array, Updated in Place: Why Loop Direction Matters
This chapter assumes you know the 0/1 knapsack recurrence and can follow the two-row compression from the previous chapter. Here we go one step further and keep a single array. The direction of the inner loop then decides whether the code is correct.
From two rows to one
The 0/1 knapsack recurrence over items i and capacities c is:
dp[i][c] = max(dp[i-1][c], dp[i-1][c-w] + v)
Each cell reads two cells of the previous row: the one directly above, and one w columns to the left. If you keep only one array, writing dp[c] overwrites the "previous row" value at index c. So the question is whether any later step in the same pass still needs that old value.
The cell dp[c] is read later by dp[c + w], which sits to the right. If you sweep from right to left, every cell that needs the old dp[c] is computed before dp[c] is overwritten.
0/1 knapsack: iterate downward
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]
print(knapsack_01([2], [3], 4)) # 3: the single item is used once
print(knapsack_01([1, 3, 4], [15, 20, 30], 4)) # 35The loop stops at w, because capacities below w cannot hold the item and keep their old values.
The upward bug
Flip the loop direction and the same code solves a different problem:
def knapsack_wrong(weights, values, capacity):
dp = [0] * (capacity + 1)
for w, v in zip(weights, values):
for c in range(w, capacity + 1):
dp[c] = max(dp[c], dp[c - w] + v)
return dp[capacity]
print(knapsack_wrong([2], [3], 4)) # 6: the item was taken twiceWhen c = 4, dp[2] has already been updated in this pass to include the item, so the item is added a second time. Nothing crashes, which makes this a common silent error.
Unbounded reuse: iterate upward on purpose
Sometimes reuse is exactly what you want. To count the ways of making an amount from coins with unlimited supply, dp[a - coin] should already include the current coin:
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(coin_change_ways([1, 2, 5], 5)) # 4With coins in the outer loop, each combination is counted once. Swapping the two loops would count ordered sequences instead, which is a different answer (9 for this input).
The rule
| Problem | Each item usable | Inner loop direction | Why |
|---|---|---|---|
| 0/1 knapsack | At most once | High to low | `dp[c - w]` must be the previous item's value |
| Unbounded knapsack, coin change | Any number of times | Low to high | `dp[c - w]` should include the current item |
Exercise
You run the downward 0/1 knapsack loop with weights [1, 2], values [10, 15], and capacity 3. What does dp contain after each item, and what is the answer? What would the upward loop return?
Show answer
After item 1 (w=1, v=10): dp = [0, 10, 10, 10]. After item 2 (w=2, v=15): dp[3] = max(10, dp[1] + 15) = 25 and dp[2] = max(10, dp[0] + 15) = 15, so dp = [0, 10, 15, 25] and the answer is 25. The upward loop lets items repeat: after item 1, dp = [0, 10, 20, 30], and item 2 cannot beat 30, so it returns 30 by taking item 1 three times.
Exercise
Why does the downward loop in knapsack_01 stop at w rather than at 0?
Show answer
For c < w the item does not fit, so dp[c] keeps its previous value. Going lower would also make c - w negative, and Python would silently index from the end of the list.