Sub topic 9
Using One Array: Why the Loop Runs Backwards
This chapter assumes you know the bottom-up table from the previous chapters. The cell dp[i][c] holds the best value you can get using the first i items with capacity c, and it is filled by the 0/1 recurrence:
dp[i][c] = max(dp[i-1][c], dp[i-1][c-w] + v), where the second option exists only when w <= c.
That table has (n+1) × (W+1) cells. With 1,000 items and a capacity of 1,000,000, it holds about a billion integers, which is far more memory than most machines can spare. The running time of O(nW) is usually acceptable. The memory is what fails first. This chapter shrinks the memory to O(W) and explains the detail that makes the smaller version correct: the capacity loop has to run from high to low.
What Each Row Actually Needs
Look at which cells the recurrence reads. Row i reads only row i-1, and it reads at most two cells there:
dp[i-1][c], the cell directly above (skip the item).dp[i-1][c-w], the cell above andwcolumns to the left (take the item).
Rows 0 through i-2 are never read again once row i-1 exists. Keeping them only matters if you later want to recover the chosen items. That cost comes up at the end of this chapter.
Step One: Two Rolling Rows
The first saving keeps only the previous row and the current row:
def knapsack_two_rows(values, weights, capacity):
prev = [0] * (capacity + 1)
for v, w in zip(values, weights):
cur = prev[:] # skip option copied for every c
for c in range(w, capacity + 1):
cur[c] = max(prev[c], prev[c - w] + v)
prev = cur
return prev[capacity]
print(knapsack_two_rows([60, 100, 120], [10, 20, 30], 50)) # 220This version is correct in either loop direction, because it reads only from prev and writes only to cur. It uses O(W) memory but copies the whole row once per item. The next step removes the copy.
Step Two: One Array, Updated in Place
Now drop cur and overwrite prev directly. The danger is this: when you compute the new dp[c], you need the old dp[c-w]. If an earlier step of the same pass has already overwritten dp[c-w] with its new value, you will be reading the current row instead of the previous one.
Every read goes to an index at or below c. So the order of the capacity loop decides what you read:
| Loop direction | When `dp[c]` is computed, `dp[c-w]` holds... | Meaning |
|---|---|---|
| High to low (`c = W ... w`) | the old value, since smaller indices have not been touched yet | item used at most once (0/1) |
| Low to high (`c = w ... W`) | the new value, which may already include this item | item can be reused (unbounded) |
Reading dp[c] itself is always safe. The right-hand side max(dp[c], ...) is evaluated before the assignment, so it sees the old value.
def knapsack_01_1d(values, weights, capacity):
dp = [0] * (capacity + 1)
for v, w in zip(values, weights):
for c in range(capacity, w - 1, -1):
dp[c] = max(dp[c], dp[c - w] + v)
return dp[capacity]
print(knapsack_01_1d([60, 100, 120], [10, 20, 30], 50)) # 220The lower bound w - 1 is deliberate. Cells with c < w cannot fit the item, so their new value equals their old value and the loop skips them. If w > capacity, the range is empty and the item is ignored, which is correct.
Watching the Bug Happen
A single item makes the difference easy to see. The item has value 3 and weight 2, and the capacity is 5. The correct answer is 3, because the item can be taken only once.
def one_pass(dp, v, w, forwards):
dp = dp[:]
cs = range(w, len(dp)) if forwards else range(len(dp) - 1, w - 1, -1)
for c in cs:
dp[c] = max(dp[c], dp[c - w] + v)
print(f" c={c}: {dp}")
return dp
start = [0] * 6
print("backwards:")
one_pass(start, 3, 2, forwards=False)
print("forwards:")
one_pass(start, 3, 2, forwards=True)Output:
backwards:
c=5: [0, 0, 0, 0, 0, 3]
c=4: [0, 0, 0, 0, 3, 3]
c=3: [0, 0, 0, 3, 3, 3]
c=2: [0, 0, 3, 3, 3, 3]
forwards:
c=2: [0, 0, 3, 0, 0, 0]
c=3: [0, 0, 3, 3, 0, 0]
c=4: [0, 0, 3, 3, 6, 0]
c=5: [0, 0, 3, 3, 6, 6]In the forward pass, dp[4] reads dp[2], which was set to 3 a moment earlier in the same pass. The result of 6 means the item was packed twice. The backward pass reads only zeros from the untouched left side, so every cell ends at 3.
Checking Against Brute Force
A randomized comparison with exhaustive search catches direction bugs, off-by-one bounds and zero-capacity edge cases:
import random
from itertools import combinations
def knapsack_01_1d(values, weights, capacity):
dp = [0] * (capacity + 1)
for v, w in zip(values, weights):
for c in range(capacity, w - 1, -1):
dp[c] = max(dp[c], dp[c - w] + v)
return dp[capacity]
def brute(values, weights, capacity):
best = 0
n = len(values)
for r in range(n + 1):
for combo in combinations(range(n), r):
if sum(weights[i] for i in combo) <= capacity:
best = max(best, sum(values[i] for i in combo))
return best
random.seed(1)
for _ in range(500):
n = random.randint(0, 8)
values = [random.randint(1, 50) for _ in range(n)]
weights = [random.randint(1, 15) for _ in range(n)]
cap = random.randint(0, 40)
assert knapsack_01_1d(values, weights, cap) == brute(values, weights, cap)
print("all 500 cases match")Loop Nesting Matters Too
The item loop must be the outer loop. Each full pass over capacities then works as one complete "row" for one item. If you swap the loops so capacity is outer and items are inner, then dp[c] is computed once from smaller cells that have already absorbed every item. That lets items repeat, and the result is again not 0/1 knapsack. In counting problems, the nesting order also decides whether you count combinations or ordered sequences, so this mistake shows up beyond knapsack.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| Answer too large, items reused | Capacity loop runs forwards | `range(capacity, w - 1, -1)` |
| Item of weight exactly `c` never taken | Lower bound written as `w` instead of `w - 1` | Stop value of `range` is exclusive |
| `IndexError` or negative index reads `dp[-k]` | Loop goes down to 0 without the `c >= w` guard | Start the range at `w` |
| Reuse even with backward loop | Capacity loop is outer, items inner | Items outer, capacity inner |
| `dp[c]` means "exactly c" by accident | Initialised with `-inf` except `dp[0]` | Use all zeros for "at most c" |
The last row of that table is a real choice, not just a bug. Initialising every cell to 0 means dp[c] is the best value with total weight at most c, and the answer is dp[W]. Initialising dp[0] = 0 and every other cell to negative infinity means exactly c, and the answer becomes max(dp). Both are valid. Mixing them up gives wrong answers.
What You Give Up
The single array drops time to O(nW) with a small constant factor and memory to O(W). The cost is that you can no longer walk back through rows to find the chosen items, because those rows are gone. You have a few ways to get the items back:
- Record decisions only. Keep a boolean
took[i][c]set when the take branch wins. It still hasn × (W+1)entries, but as a bit array it is 32 to 64 times smaller than storing integers. - Divide and conquer. Split the items in half, run the one-array DP forwards on the first half and on the second half, find the capacity split that achieves the optimum, then recurse on each half. This recovers the items in O(W) extra memory for about twice the time, using the same idea as Hirschberg's algorithm for sequence alignment.
- Value only. If you only need the optimal value, as in many contest and pricing problems, the one-array version is all you need.
Exercise
With one array and a backward loop, process items (value 5, weight 1) and (value 4, weight 2) with capacity 3, starting from dp = [0, 0, 0, 0]. Give dp after each item, then say what a forward loop would return for capacity 3.
Show answer
After item 1 (backwards): dp = [0, 5, 5, 5]. After item 2, going c = 3, 2: dp[3] = max(5, dp[1] + 4) = 9, dp[2] = max(5, dp[0] + 4) = 5, so dp = [0, 5, 5, 9]. The answer is 9, from taking both items. With forward loops, item 1 gives [0, 5, 10, 15] because it is reused. Item 2 then cannot beat those values (for example dp[3] = max(15, dp[1] + 4) = 15), so the forward loop returns 15, which is the unbounded answer.
Exercise
A colleague writes for c in range(capacity, w, -1) in the 0/1 one-array DP. For values [10], weights [4], capacity 4, what does the function return, and why?
Show answer
It returns 0 instead of 10. The range stop is exclusive, so c runs from 4 down to 5, which is empty, and the cell c = 4 = w is never updated. The stop must be w - 1 so that c = w is included.
Exercise
Why is reading dp[c] on the right-hand side safe in both loop directions, while reading dp[c - w] is safe only when the loop goes backwards?
Show answer
In both directions, dp[c] has not been written yet in the current pass when its own update is evaluated, so it still holds the previous item's value. dp[c - w] sits at a smaller index. A forward loop has already overwritten it in this pass, so it may include the current item. A backward loop has not reached it yet.