AlgoViz

Unbounded knapsack

medium 20 min

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

See it run

Every item can be packed again and again, so one row dp[w] filled left to right is enough: watch it solve the knapsack, coin change, counting ways and rod cutting.

Operations

Unbounded knapsack: best value

dp[w] is the best value that fits in capacity w using any number of copies of each item. For each capacity, try every item as the last one packed: v_i + dp[w - w_i]. The smaller capacity is already final and may already contain the same item, which is what makes reuse free.

Step 1 of 10

Items and an empty table

dp[w]

  1. 00
  2. ·1
  3. ·2
  4. ·3
  5. ·4
  6. ·5
  7. ·6
  8. ·7
items = A (w 2, v 4) · B (w 3, v 5) · C (w 4, v 7)W = 7

Items A (weight 2, value 4), B (3, 5) and C (4, 7), each available as many times as we like. Capacity W = 7. dp[0] = 0: an empty bag is worth nothing. Every other cell starts at 0 too, because packing nothing is always allowed.

Step 1: Items and an empty table

def unbounded_knapsack(weights, values, W):    dp = [0] * (W + 1)                    # dp[w] = best value with capacity w    for w in range(1, W + 1):             # capacities left to right        for wi, vi in zip(weights, values):            if wi <= w:                # dp[w - wi] is already final, and may already hold item i                dp[w] = max(dp[w], vi + dp[w - wi])    return dp[W]
Time
O(n · W)
Space
O(W)
Same items, 0/1 knapsack
12 (B + C)
Unbounded
13 (A + A + B)
Greedy by value per weight
12 (A + A + A)

Say the state and the choice: dp[w] is the best value for capacity w, and the last item packed can be any item that fits, because the rest of the bag is dp[w - w_i].

In the real world

The same unbounded knapsack doing real jobs. Pick one and step through it.

A rod of length 8 and a price list for each piece length. Cut it into pieces of any lengths, any length as often as you like, to earn the most. The piece lengths are the items, their prices the values, the rod length the capacity.

Step 1 of 5

Prices and the base case

best[n]

  1. 00
  2. ·1
  3. ·2
  4. ·3
  5. ·4
  6. ·5
  7. ·6
  8. ·7
  9. ·8

price of one piece

  1. –0
  2. 11
  3. 52
  4. 83
  5. 94
  6. 105
  7. 176
  8. 177
  9. 208
rod length = 8

Prices for lengths 1 to 8: 1, 5, 8, 9, 10, 17, 17, 20. best[0] = 0. A piece of length k sold whole earns price[k], but cutting may earn more.

Step 1: Prices and the base case

def rod_cutting(price, n):    best = [0] * (n + 1)                  # best[k] = most money for length k    for k in range(1, n + 1):        for cut in range(1, k + 1):       # first piece has length cut            best[k] = max(best[k], price[cut] + best[k - cut])    return best[n]

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Looping capacities backwards

    critical

    A right-to-left loop reads cells that do not include the current item yet, so each item is used at most once. That solves 0/1 knapsack, not this one: one item (2, 4) and W = 6 gives 4 instead of 12.

    Wrong
    for wi, vi in zip(weights, values):    for w in range(W, wi - 1, -1):      # backwards: 0/1        dp[w] = max(dp[w], vi + dp[w - wi])
    Right
    for wi, vi in zip(weights, values):    for w in range(wi, W + 1):          # forwards: unbounded        dp[w] = max(dp[w], vi + dp[w - wi])
  • Starting coin change at 0 instead of infinity

    critical

    With every cell at 0, min(dp[a], dp[a - c] + 1) keeps 0 forever and the answer is always 0. Unreached amounts must start at infinity so any real count beats them.

    Wrong
    dp = [0] * (amount + 1)for a in range(1, amount + 1):    for c in coins:        if c <= a:            dp[a] = min(dp[a], dp[a - c] + 1)   # stays 0
    Right
    dp = [0] + [float("inf")] * amountfor a in range(1, amount + 1):    for c in coins:        if c <= a:            dp[a] = min(dp[a], dp[a - c] + 1)
  • Returning infinity when no answer exists

    major

    If no coin mix reaches the amount, dp[amount] is still infinity. The problem wants -1, and printing inf or casting it to int fails.

    Wrong
    return dp[amount]                        # coins [2], amount 3: inf
    Right
    return dp[amount] if dp[amount] != float("inf") else -1
  • Counting ways with the loops swapped

    critical

    Amount outside and coins inside counts every ordering separately: change(5, [1, 2, 5]) returns 9 instead of 4. Put the coins in the outer loop to count each combination once.

    Wrong
    for a in range(1, amount + 1):    for c in coins:                     # counts 1+2 and 2+1 twice        if c <= a:            dp[a] += dp[a - c]
    Right
    for c in coins:                         # each multiset once    for a in range(c, amount + 1):        dp[a] += dp[a - c]
  • Seeding the count with dp[0] = 0

    major

    Counting tables only ever add, so if nothing is 1 to begin with every cell stays 0. The empty selection is one valid way to make 0.

    Wrong
    dp = [0] * (amount + 1)                 # every answer is 0
    Right
    dp = [0] * (amount + 1)dp[0] = 1                               # one way: no coins
  • Greedy: biggest coin or best ratio first

    major

    Greedy works for some coin systems (1, 5, 10, 25) but not in general: coins [1, 3, 4] and amount 6 give 4 + 1 + 1 instead of 3 + 3. For the knapsack, best value per weight can leave capacity unused (A, B, C example: 12 instead of 13).

    Wrong
    def coins_greedy(coins, amount):    count = 0    for c in sorted(coins, reverse=True):        count += amount // c        amount %= c    return count                        # [1, 3, 4], 6 gives 3
    Right
    def coin_change(coins, amount):    dp = [0] + [float("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] != float("inf") else -1   # 2

Interview tips

  • How to explain it

    • dp[w] is the best value for capacity w; dp[0] = 0.
    • The last item packed can be any item that fits: dp[w] = max over i of v_i + dp[w - w_i].
    • Fill w from small to large, so dp[w - w_i] is final and may already contain item i.
    • O(n · W) time and O(W) space; W is a number, so this is pseudo-polynomial.
  • Spot it in problems

    • Unlimited supply of each item, coin or piece length.
    • Fewest coins (min), count the ways (+=), most value (max), any reachable (or).
    • Rod cutting, integer break, perfect squares, minimum cost for tickets.
    • Ordered sequences (1 + 2 differs from 2 + 1): amount outside, items inside.
  • Memory tricks

    • Forward = reuse; backward = once.
    • Unbounded reads the same row, 0/1 reads the row above.
    • Coin change II: coins outside count combinations, amount outside counts permutations.
    • Know cold: coins [1, 2, 5], amount 11 gives 3 coins; amount 5 has 4 ways.
  • Watch out

    • Min problems start at infinity, count problems start with dp[0] = 1.
    • Return -1 when the amount is unreachable.
    • Greedy is only safe for special coin systems.
    • Big W (say 10^9) makes the table impossible; look for another approach.