Sub topic 10
Unbounded Knapsack: Reusing Items
This chapter assumes you have read the earlier chapters on the 0/1 recurrence, the bottom-up table and the one-dimensional array. You should know why the 0/1 version runs its capacity loop backwards. Here we drop the rule that each item can be packed at most once. Every item type now has an unlimited supply, and you may take any whole number of copies.
The Problem Statement
You have n item types. Type i has value v_i and weight w_i, where w_i > 0. Choose non-negative integer counts x_i that maximize the total value sum(v_i * x_i), subject to sum(w_i * x_i) <= W.
This model fits stock cutting, coin systems, and resource packing where you draw from an effectively unlimited supply. The only change from 0/1 knapsack is that x_i can be any non-negative integer instead of only 0 or 1.
Greedy Still Fails
Taking copies of the item with the best value-to-weight ratio sounds reasonable now that supply is unlimited. It is still wrong, because whole copies leave unused capacity at the end. Take capacity 4 and two item types:
| Item | Value | Weight | Ratio |
|---|---|---|---|
| A | 5 | 3 | 1.67 |
| B | 3 | 2 | 1.50 |
Greedy takes one A for value 5, and the leftover capacity of 1 fits nothing. Two copies of B weigh 4 and are worth 6. So you still need dynamic programming.
Changing the Recurrence
In the 2D table for 0/1 knapsack, dp[i][c] is the best value using only the first i items with capacity c:
dp[i][c] = max(dp[i-1][c], dp[i-1][c - w] + v)The take branch reads row i-1, which means "item i is no longer available." For unbounded knapsack, taking a copy of item i leaves item i still available. The take branch reads the same row:
dp[i][c] = max(dp[i-1][c], dp[i][c - w] + v) if w <= cThe change is one index, from i-1 to i. It is also correct by optimal substructure: if the best packing for capacity c holds at least one copy of item i, then removing that copy leaves a best packing for c - w that may still use item i.
A second formulation drops the item dimension altogether:
dp[c] = max(0, max over all i with w_i <= c of (v_i + dp[c - w_i]))This says the best packing for capacity c is the best choice of a final item added to the best packing of what remains.
One Array, Forward Loop
In the one-dimensional 0/1 code, the backward loop made sure that dp[c - w] still held the previous row's value when it was read. For unbounded knapsack you want dp[c - w] to already include the current item, which is exactly what a forward loop provides:
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 knapsack_unbounded(values, weights, capacity):
dp = [0] * (capacity + 1)
for v, w in zip(values, weights):
for c in range(w, capacity + 1):
dp[c] = max(dp[c], dp[c - w] + v)
return dp[capacity]
print(knapsack_01_1d([60, 100, 120], [10, 20, 30], 50)) # 220
print(knapsack_unbounded([60, 100, 120], [10, 20, 30], 50)) # 300On the tutorial's standard input, the unbounded answer is 300: five copies of the first item. The forward loop builds those copies one at a time, as the diagram shows.
Time is O(nW) and space is O(W), the same as 0/1.
Recovering the Counts
The 0/1 reconstruction compared neighbouring rows, and that does not carry over to a single array. A simpler approach is to record which item last improved each cell, then follow those records back from capacity.
def unbounded_with_counts(values, weights, capacity):
dp = [0] * (capacity + 1)
last = [-1] * (capacity + 1) # item that produced dp[c], or -1 for none
for c in range(1, capacity + 1):
for i, (v, w) in enumerate(zip(values, weights)):
if w <= c and dp[c - w] + v > dp[c]:
dp[c] = dp[c - w] + v
last[c] = i
counts = [0] * len(values)
c = capacity
while last[c] != -1:
i = last[c]
counts[i] += 1
c -= weights[i]
return dp[capacity], counts
print(unbounded_with_counts([60, 100, 120], [10, 20, 30], 50)) # (300, [5, 0, 0])This code puts capacity in the outer loop to match the "last item added" recurrence. The walk-back always ends, because every step lowers c by a positive weight. It stops at a cell that no item improved, so any capacity left over at that point is unused space.
Edge Cases and Gotchas
Loop nesting order
When you maximize value, you can nest the loops either way: items outside and capacity inside, or the reverse. Both orders consider every multiset of items. When you count solutions, the order changes what you count. The classic example is coin change:
def count_combinations(coins, amount):
ways = [1] + [0] * amount
for coin in coins: # items outer: each multiset counted once
for c in range(coin, amount + 1):
ways[c] += ways[c - coin]
return ways[amount]
def count_sequences(coins, amount):
ways = [1] + [0] * amount
for c in range(1, amount + 1): # capacity outer: each ordering counted
for coin in coins:
if coin <= c:
ways[c] += ways[c - coin]
return ways[amount]
print(count_combinations([1, 2, 5], 5)) # 4
print(count_sequences([1, 2, 5], 5)) # 9With items in the outer loop, coins are added in a fixed order, so 2+2+1 and 1+2+2 count as one way. With capacity in the outer loop, any coin can be the last one added, so every ordering is counted separately.
"At most" versus "exactly"
Starting with dp = [0] * (W + 1) means "total weight at most c." If the knapsack must be filled exactly, start with dp[0] = 0 and every other cell at float('-inf'). Then unreachable capacities stay at -inf. With a single item of weight 4 and capacity 6, the "at most" answer is that item's value. The "exactly" answer is -inf, because no combination of 4s adds up to 6. The minimum-coins problem follows the same pattern: use min, start the other cells at float('inf'), and add 1 per coin.
Zero-weight items
If an item has w = 0 and v > 0, the true answer is infinite. The forward loop then becomes range(0, ...) and updates dp[c] from itself only once, so it returns a finite but wrong value. Check that every weight is positive at the input boundary.
Dominated items
If item j weighs at least as much as item i and is worth no more, then item j is never needed, because you could always swap it for a copy of i. Removing dominated items first shrinks n without changing the answer. With unlimited supply this pruning is always safe. In 0/1 knapsack it is not, because you may need both items.
Comparison with 0/1
| Aspect | 0/1 | Unbounded |
|---|---|---|
| Count per item | 0 or 1 | Any non-negative integer |
| 2D take branch | `dp[i-1][c-w]` | `dp[i][c-w]` |
| 1D capacity loop | Backward | Forward |
| Loop nesting (max value) | Items must be outer | Either order |
| Time / space | `O(nW)` / `O(W)` | `O(nW)` / `O(W)` |
Exercise
Values [5, 3], weights [3, 2], capacity 7. Fill the unbounded dp array for c = 0..7 using the forward loop with items in order, and state the optimal counts.
Show answer
After item A (w=3, v=5): [0,0,0,5,5,5,10,10]. After item B (w=2, v=3): c=2→3, c=3→5, c=4→max(5,3+3)=6, c=5→max(5,5+3)=8, c=6→max(10,6+3)=10, c=7→max(10,8+3)=11. Final dp = [0,0,3,5,6,8,10,11]. The answer is 11: one A and two B (weight 3+4=7, value 5+6=11).
Exercise
A colleague's unbounded knapsack returns 220 on values [60, 100, 120], weights [10, 20, 30], capacity 50. What is the most likely bug?
Show answer
The capacity loop runs backwards (from capacity down to w), which is the 0/1 iteration order. Each item is then used at most once, so the result is the 0/1 optimum of 220 instead of the unbounded optimum of 300. Change the loop to range(w, capacity + 1).
Exercise
Why does countcombinations([1, 2], 3) return 2 while countsequences([1, 2], 3) returns 3?
Show answer
The combinations are {1,1,1} and {1,2}. Counting orderings separates {1,2} into 1+2 and 2+1, giving 1+1+1, 1+2 and 2+1. With items in the outer loop, coins are added in a fixed order, so each multiset is counted once. With capacity in the outer loop, any coin can be the last one added, so each ordering is counted.