Unbounded knapsack
medium 20 minThe knapsack where every item can be taken as many times as you like.
Video lesson · Chapter 1 of 9
The supply dispenser
Unbounded knapsack in 75 seconds
1:25Reel
How it works
Step through the idea, or press Play.
Pick the last item. Any item that fits can be the last one packed; the rest of the bag is dp[w - w_i]
Understand it
Start here
One of each, or as many as you like
Recap: DP
Define a state, write how it is built from smaller states, fill in an order where the smaller ones come first. See Dynamic programming: the core idea.
Recap: 0/1 knapsack
Each item is taken at most once:
dp[i][w] = max(dp[i-1][w], v_i + dp[i-1][w - w_i]). Covered in 0/1 knapsack.This topic: unlimited copies
Same items, same bag, but every item has an endless supply. The foundation of coin change and rod cutting.
You have items with weights and values , and a bag of capacity . Pack copies of any items, as many of each as you like, so the total weight is at most and the total value is as large as possible. The running example: A (weight 2, value 4), B (3, 5), C (4, 7) and .
| Bag | Weight | Value | Allowed in 0/1? | Allowed here? |
|---|---|---|---|---|
| B + C | 7 | 12 | yes | yes |
| A + A + A | 6 | 12 | no | yes |
| A + A + B | 7 | 13 | no | yes |
| C + A | 6 | 11 | yes | yes |
The recurrence
dp[w] = max over items of v_i + dp[w − w_i]
Best value for capacity w
Filling one cell
dp[w - w_i] is the best way to fill what remains, with every item still available.Why it is right. Take an optimal bag for capacity that holds at least one item, and pick any item in it. Remove one copy: what remains weighs at most and uses any items, so it is worth at most . Hence the bag is worth at most , and that value is reachable by adding a copy of to the best smaller bag. The max over all is therefore exact: optimal substructure with a single index.
Worked example
Filling dp for A, B, C and W = 7
| w | A: 4 + dp[w−2] | B: 5 + dp[w−3] | C: 7 + dp[w−4] | dp[w] |
|---|---|---|---|---|
| 0 | – | – | – | 0 |
| 1 | – | – | – | 0 |
| 2 | 4 | – | – | 4 |
| 3 | 4 | 5 | – | 5 |
| 4 | 4 + 4 = 8 | 5 | 7 | 8 |
| 5 | 4 + 5 = 9 | 5 + 4 = 9 | 7 | 9 |
| 6 | 4 + 8 = 12 | 10 | 11 | 12 |
| 7 | 4 + 9 = 13 | 5 + 8 = 13 | 7 + 5 = 12 | 13 |
dp[2] already holds an A, so A + A = 8. Walking back from 7 (A, then A from 5, then B from 3) gives the bag A + A + B.def unbounded_knapsack(weights, values, W): dp = [0] * (W + 1) # dp[w] = best value for capacity w for w in range(1, W + 1): for wi, vi in zip(weights, values): if wi <= w: dp[w] = max(dp[w], vi + dp[w - wi]) return dp[W]print(unbounded_knapsack([2, 3, 4], [4, 5, 7], 7)) # 13print(unbounded_knapsack([5], [10], 4)) # 0, nothing fitsThe key detail
Loop direction: forwards reuses, backwards does not
Both knapsacks fit in one row and run the same line dp[w] = max(dp[w], v + dp[w - wi]) once per item. The cell they read, dp[w - wi], is always to the left. So the order of w decides what that cell contains when it is read.
One item (2, 4), capacity 6, in both directions
Forward (unbounded)
for w in range(wi, W + 1)dp[w - wi]is already updated for this item, so copies stack.- Items-outside and capacities-outside orders both work.
Backward (0/1)
for w in range(W, wi - 1, -1)dp[w - wi]is still from before this item, so it counts once.- Needs items outside; see 0/1 knapsack.
2D view
Complete knapsack in 2D, folded into 1D
Item prefixes as rows
| Items / w | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| none | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| +A (2, 4) | 0 | 0 | 4 | 4 | 8 | 8 | 12 | 12 |
| +B (3, 5) | 0 | 0 | 4 | 5 | 8 | 9 | 12 | 13 |
| +C (4, 7) | 0 | 0 | 4 | 5 | 8 | 9 | 12 | 13 |
[0, 0, 4, 4, 4, 4, 4, 4] in row A and 12 in the corner.Where each cell reads from
Variant 1
Coin change: the fewest coins
Coins of given values, unlimited of each; make amount with as few coins as possible, or return -1. Coins are items with value 1 each, we minimise, and the bag must be filled exactly. The original app's example: coins [1, 2, 5], amount 11.
Fewest coins for amount a
| a | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| dp[a] | 0 | 1 | 1 | 2 | 2 | 1 | 2 | 2 | 3 | 3 | 2 | 3 |
dp[6] + 1 = 3, coin 2 gives dp[5] + 1 = 2, coin 5 gives dp[2] + 1 = 2, so dp[7] = 2. dp[11] = 3, using 5 + 5 + 1.def coin_change(coins, amount): INF = float("inf") dp = [0] + [INF] * amount for a in range(1, amount + 1): for c in coins: if c <= a: dp[a] = min(dp[a], dp[a - c] + 1) return dp[amount] if dp[amount] != INF else -1print(coin_change([1, 2, 5], 11)) # 3print(coin_change([1, 3, 4], 6)) # 2 (greedy would say 3)print(coin_change([2], 3)) # -1Variant 2
Coin change II: counting the ways
Now count how many different multisets of coins make the amount. dp[0] = 1 (the empty selection) and each coin adds dp[a - c] ways. The loop order is no longer free: it decides whether 1 + 2 and 2 + 1 count once or twice.
Combinations or permutations?
def change(amount, coins): # combinations dp = [0] * (amount + 1) dp[0] = 1 for c in coins: for a in range(c, amount + 1): dp[a] += dp[a - c] return dp[amount]def ordered_ways(amount, coins): # permutations dp = [0] * (amount + 1) dp[0] = 1 for a in range(1, amount + 1): for c in coins: if c <= a: dp[a] += dp[a - c] return dp[amount]print(change(5, [1, 2, 5])) # 4: 5, 2+2+1, 2+1+1+1, 1+1+1+1+1print(ordered_ways(5, [1, 2, 5])) # 9| Coin change I | Coin change II | |
|---|---|---|
| Goal | Fewest coins | Number of ways |
| dp[0] | 0 | 1 |
| Other cells start at | ∞ | 0 |
| Update | min(dp[a], dp[a - c] + 1) | dp[a] += dp[a - c] |
| Loop order matters? | No | Yes: coins outside |
Family
Rod cutting and other relatives
Rod cutting: a rod of length and a price for each piece length; cut it to earn the most. Piece lengths are items, prices are values, the rod is the capacity, and the rod must be used up exactly (pieces of length 1 make that free). With prices 1, 5, 8, 9, 10, 17, 17, 20 for lengths 1 to 8, the best for length 8 is 22, from pieces 2 + 6.
| Problem | Items | Combine | dp[0] | Recurrence |
|---|---|---|---|---|
| Unbounded knapsack | (w_i, v_i) | max | 0 | max(dp[w], v_i + dp[w - w_i]) |
| Coin change I | coin values | min | 0, rest ∞ | min(dp[a], dp[a - c] + 1) |
| Coin change II | coin values | sum | 1, rest 0 | dp[a] += dp[a - c] |
| Rod cutting | piece lengths | max | 0 | max(best[n], price[k] + best[n - k]) |
| Integer break | parts 1..n-1 | max product | – | max(dp[i], j * max(i - j, dp[i - j])) |
| Perfect squares | 1, 4, 9, ... | min | 0 | min(dp[a], dp[a - s] + 1) |
max(i - j, dp[i - j]) because a part may stay unsplit.def rod_cutting(price, n): """price[k] = price of a piece of length k (price[0] unused).""" best = [0] * (n + 1) for k in range(1, n + 1): for cut in range(1, k + 1): best[k] = max(best[k], price[cut] + best[k - cut]) return best[n]prices = [0, 1, 5, 8, 9, 10, 17, 17, 20]print(rod_cutting(prices, 4)) # 10 (2 + 2)print(rod_cutting(prices, 8)) # 22 (2 + 6)Cost
O(n · W) and why it is pseudo-polynomial
Time and space
| Approach | Time | Space | Notes |
|---|---|---|---|
| Brute force (try every count of every item) | Exponential | stack | Branches on each item at each capacity |
Memoised best(w) | + stack | Direct from the recurrence; recursion depth up to | |
2D table dp[i][w] | Shows the same-row read clearly | ||
| 1D table, forward | The version to write |
Spotting it
Which knapsack is this?
Choosing the table
- 1Statedp[w] for each budget
- 2Basedp[0] = 0 or 1
- 3Fill forwardtry every item last
- 4Answerdp[W]
Recap
Key takeaways
Key points
- Unbounded knapsack: every item can be taken any number of times.
- dp[w] = max over items that fit of v_i + dp[w - w_i], with dp[0] = 0; answer dp[W].
- Fill w from small to large: dp[w - w_i] is final and may already contain item i.
- In 1D, forward loops reuse items (unbounded) and backward loops use them once (0/1).
- In 2D, the take reads the same row dp[i][w - w_i]; 0/1 reads the row above.
- Coin change I: min of dp[a - c] + 1, start at infinity, return -1 if unreachable. [1, 2, 5] and 11 give 3.
- Coin change II: dp[0] = 1, dp[a] += dp[a - c], coins outside for combinations (4 ways for 5), amount outside for permutations (9).
- Rod cutting, integer break and perfect squares share the skeleton. Cost O(n · W) time, O(W) space, pseudo-polynomial.