AlgoViz

Unbounded knapsack

medium 20 min

The knapsack where every item can be taken as many times as you like.

Video lesson · Chapter 1 of 9

The supply dispenser

0:00 / 7:08

Unbounded knapsack in 75 seconds

1:25Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

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 wiw_i and values viv_i, and a bag of capacity WW. Pack copies of any items, as many of each as you like, so the total weight is at most WW and the total value is as large as possible. The running example: A (weight 2, value 4), B (3, 5), C (4, 7) and W=7W = 7.

BagWeightValueAllowed in 0/1?Allowed here?
B + C712yesyes
A + A + A612noyes
A + A + B713noyes
C + A611yesyes
Reuse lifts the best from 12 to 13. The tie between B + C and three A's also shows why value per weight alone is not enough.

The recurrence

dp[w] = max over items of v_i + dp[w − w_i]

Best value for capacity w

dp[w]=max⁡(0, max⁡i : wi≤w(vi+dp[w−wi])),dp[0]=0\text{dp}[w] = \max\Big(0,\ \max_{i\,:\,w_i \le w} \big(v_i + \text{dp}[w - w_i]\big)\Big), \qquad \text{dp}[0] = 0
Answer: dp[W]\text{dp}[W]. The 0 covers bags where nothing fits. Each cell reads only smaller capacities, so filling w=1,2,…,Ww = 1, 2, \dots, W in order always has its inputs ready.

Filling one cell

Every item gets a turn as the last item packed. 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 ww that holds at least one item, and pick any item ii in it. Remove one copy: what remains weighs at most w−wiw - w_i and uses any items, so it is worth at most dp[w−wi]\text{dp}[w - w_i]. Hence the bag is worth at most vi+dp[w−wi]v_i + \text{dp}[w - w_i], and that value is reachable by adding a copy of ii to the best smaller bag. The max over all ii is therefore exact: optimal substructure with a single index.

Worked example

Filling dp for A, B, C and W = 7

wA: 4 + dp[w−2]B: 5 + dp[w−3]C: 7 + dp[w−4]dp[w]
0–––0
1–––0
24––4
345–5
44 + 4 = 8578
54 + 5 = 95 + 4 = 979
64 + 8 = 12101112
74 + 9 = 135 + 8 = 137 + 5 = 1213
Row 4 is the first reuse: 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.
Python
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 fits
Capacities outside, items inside, exactly as the table was filled. O(n⋅W)O(n \cdot W) time, O(W)O(W) space.
Edit and run it in your browser

The 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 reads values that already include this item; backward reads values from before it.

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

dp[i][w]=max⁡(dp[i−1][w]⏟no more of item i, vi+dp[ i ][w−wi]⏟one more copy of i)\text{dp}[i][w] = \max\big(\underbrace{\text{dp}[i-1][w]}_{\text{no more of item } i},\ \underbrace{v_i + \text{dp}[\,\mathbf{i}\,][w - w_i]}_{\text{one more copy of } i}\big)
The take reads the same row ii, so item ii is still available. 0/1 reads row i−1i - 1 instead. That one index is the entire difference in 2D.
Items / w01234567
none00000000
+A (2, 4)0044881212
+B (3, 5)0045891213
+C (4, 7)0045891213
The 2D table for the running example. The 0/1 table has [0, 0, 4, 4, 4, 4, 4, 4] in row A and 12 in the corner.

Where each cell reads from

In one row, a cell not yet overwritten still holds row i−1i - 1. Which neighbours must be new decides the loop direction.

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

dp[a]=min⁡c ∈ coins, c≤a(dp[a−c]+1),dp[0]=0,  dp[a]=∞ until reached\text{dp}[a] = \min_{c \,\in\, \text{coins},\ c \le a} \big(\text{dp}[a - c] + 1\big), \qquad \text{dp}[0] = 0,\ \ \text{dp}[a] = \infty \text{ until reached}
Infinity marks amounts no coin mix has reached yet, and stays if none ever does. That is how -1 is detected at the end.
a01234567891011
dp[a]011221223323
For a=7a = 7: coin 1 gives 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.
Python
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))          # -1
Coin change (LeetCode 322 style). Same skeleton as the knapsack with min, + 1 and infinity.
Edit and run it in your browser

Variant 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?

Coin change II is the left branch. The right branch is Climbing stairs with step sizes 1, 2 and 5.
Python
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
Both loop orders side by side on amount 5.
Edit and run it in your browser
Coin change ICoin change II
GoalFewest coinsNumber of ways
dp[0]01
Other cells start at∞0
Updatemin(dp[a], dp[a - c] + 1)dp[a] += dp[a - c]
Loop order matters?NoYes: coins outside
The original app's comparison, with the loop-order row added.

Family

Rod cutting and other relatives

Rod cutting: a rod of length nn 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.

ProblemItemsCombinedp[0]Recurrence
Unbounded knapsack(w_i, v_i)max0max(dp[w], v_i + dp[w - w_i])
Coin change Icoin valuesmin0, rest ∞min(dp[a], dp[a - c] + 1)
Coin change IIcoin valuessum1, rest 0dp[a] += dp[a - c]
Rod cuttingpiece lengthsmax0max(best[n], price[k] + best[n - k])
Integer breakparts 1..n-1max product–max(dp[i], j * max(i - j, dp[i - j]))
Perfect squares1, 4, 9, ...min0min(dp[a], dp[a - s] + 1)
One skeleton, different operators. Integer break needs max(i - j, dp[i - j]) because a part may stay unsplit.
Python
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)
Rod cutting is the knapsack with weight = length.
Edit and run it in your browser

Cost

O(n · W) and why it is pseudo-polynomial

Time and space

T(n,W)=∑w=1W∑i=1nO(1)=O(n⋅W),S=O(W+1)=O(W)T(n, W) = \sum_{w=1}^{W} \sum_{i=1}^{n} O(1) = O(n \cdot W), \qquad S = O(W + 1) = O(W)
For A, B, C and W=7W = 7 that is 21 item checks. Coin change with 3 coins and amount 11 is 33.
ApproachTimeSpaceNotes
Brute force (try every count of every item)ExponentialO(W)O(W) stackBranches on each item at each capacity
Memoised best(w)O(n⋅W)O(n \cdot W)O(W)O(W) + stackDirect from the recurrence; recursion depth up to WW
2D table dp[i][w]O(n⋅W)O(n \cdot W)O(n⋅W)O(n \cdot W)Shows the same-row read clearly
1D table, forwardO(n⋅W)O(n \cdot W)O(W)O(W)The version to write

Spotting it

Which knapsack is this?

Choosing the table

Every unbounded branch fills one row of size W+1W + 1 forwards.
The method
  1. 1Statedp[w] for each budget
  2. 2Basedp[0] = 0 or 1
  3. 3Fill forwardtry every item last
  4. 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.

Sources