0/1 knapsack in one array: why loop capacity downwards?
Question
A courier's bag holds 4 kg. Each parcel can go in at most once and pays a fee:
| parcel | weight | fee |
|---|---|---|
| A | 1 kg | $3 |
| B | 2 kg | $5 |
| C | 3 kg | $7 |
The code below keeps one array, best, and should return the highest total fee. The right answer is 10: parcels A and C. The code returns 12.
Where does 12 come from? Which one-line change fixes it, and why does that change work?
def best_fee(parcels, capacity): best = [0] * (capacity + 1) # best[c]: top fee with weight <= c for weight, fee in parcels: for c in range(weight, capacity + 1): best[c] = max(best[c], best[c - weight] + fee) return best[capacity] print(best_fee([(1, 3), (2, 5), (3, 7)], 4)) # 12, but should be 10
Show hints (3)
- "READ THE NUMBER"
Which set of parcels could pay $12 in a 4 kg bag? Try using one of them more than once.
- "WHAT BEST[C - WEIGHT] HOLDS"
When the loop goes upwards and reaches
best[2], it readsbest[1]. Wasbest[1]already updated for the parcel you are adding right now? - "CHANGE THE ORDER"
If the loop visits big capacities first, the smaller cell it reads has not been touched by the current parcel yet. Try
range(capacity, weight - 1, -1).
Show checked explanation
12 is parcel A packed four times. Going upwards, best[c - weight] already includes the current parcel, so the code can add it again. Loop capacity downwards instead: range(capacity, weight - 1, -1). Then every cell you read still holds the answer without the current parcel, so each parcel is used at most once.
def best_fee(parcels, capacity): best = [0] * (capacity + 1) # best[c]: top fee with weight <= c for weight, fee in parcels: for c in range(capacity, weight - 1, -1): # downwards best[c] = max(best[c], best[c - weight] + fee) print(f"after the {weight} kg parcel: {best}") return best[capacity] print(best_fee([(1, 3), (2, 5), (3, 7)], 4))
after the 1 kg parcel: [0, 3, 3, 3, 3] after the 2 kg parcel: [0, 3, 5, 8, 8] after the 3 kg parcel: [0, 3, 5, 8, 10] 10
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
best[c] is the highest fee for a bag of c kg, using the parcels seen so far. Here is parcel A (1 kg, $3) going into the array of zeros, in both directions:
| loop | best[1] | best[2] | best[3] | best[4] |
|---|---|---|---|---|
| upwards | 0 + 3 = 3 | 3 + 3 = 6 | 6 + 3 = 9 | 9 + 3 = 12 |
| downwards | 0 + 3 = 3 | 0 + 3 = 3 | 0 + 3 = 3 | 0 + 3 = 3 |
Upwards, best[2] reads best[1], which already holds parcel A. So 6 means A twice, and 12 means A four times. There is only one parcel A, so 12 is impossible.
Downwards, the loop updates best[4] first. It reads best[3], which is still 0 from before parcel A. Each cell reads a smaller cell, and smaller cells are updated later. So every read sees the array as it was before this parcel. That is the previous row of the usual 2D table, kept in the same array.
After all three parcels the array is [0, 3, 5, 8, 10]. The 10 is A and C: 4 kg and $10 together.
Upwards is not always wrong. It is the right loop when each parcel can be packed any number of times. That is the unbounded knapsack, and there 12 is the correct answer.
Time is O(n × capacity) and memory is O(capacity), where n is the number of parcels. This is called pseudo-polynomial: it grows with the capacity's value, not with the number of digits needed to write it. Weigh parcels in grams with a 20 kg bag, and the array has 20,001 cells, even for three parcels.
Common mistakes
- Copying the upward loop from an unbounded knapsack or coin change solution. In 0/1 knapsack it packs a parcel more than once: the example returns 12 instead of 10.
- Running the downward loop down to 0 instead of to
weight. Thenc - weightgoes negative, and Python reads from the end of the list without an error. The example returns 20. - Filling every cell with 0 when the bag must be filled exactly. 2 kg and 3 kg parcels can't fill exactly 4 kg, yet zeros give $7. Start every cell except
best[0]at minus infinity.
Follow-up questions
- "Which parcels did you pick?" One array can't tell you, because old values get overwritten. Keep a 2D table
took[i][c]that is true when parceliimproved cellc. Walk back from the last parcel: if it was taken atc, record it and subtract its weight. Here you get C, then A. - "Each parcel now comes in unlimited copies." Loop upwards. Reading a cell that already includes the current parcel is now exactly what you want. The example answer becomes 12: four copies of A. Coin change with unlimited coins uses the same upward loop.
What a strong answer covers
Explains that the loop direction decides which version of best[c - weight] is read. Shows on a tiny example that upwards packs one parcel twice. Knows upwards is the unbounded knapsack, calls O(n × capacity) pseudo-polynomial and starts an exact fill from minus infinity.
Open in interactive practice deck →