Skip to content
Visual explainer 3h 30m to learn 4 steps

Knapsack problems

Solve 0/1 and unbounded knapsack and map subset-sum and coin-change problems onto them.

By Invicly Tech, , in Data Structures & Algorithms. About 13 minutes to read.

Topic 42 of 54

In short

In 0/1 knapsack each item can be taken at most once to maximise value within a weight capacity. The state is the best value for each capacity using the items seen so far. Many problems are knapsack in disguise, including subset sum, equal partition and coin change.

Explained simply

You are packing a backpack for a hike. It can carry at most 7 kg. Each item has a weight and a value to you. You cannot cut items in half. Which items should you take to get the most value? That is the 0/1 knapsack problem: each item is either in (1) or out (0).

Trying every combination works for a few items, but n items have 2^n combinations, over a million for just 20 items. DP is much faster when the weights are whole numbers and the capacity is not huge. It asks: what is the best value for every capacity from 0 to 7, using the items seen so far?

For each new item, every capacity has two choices. Skip the item and keep the old best. Or take it, which uses up its weight, and add its value to the best for the smaller capacity left over. Keep whichever is larger.

Many problems are knapsack wearing a costume. Can these numbers be split into two equal halves? Can some of them add up to a target? What is the fewest number of coins to make an amount? The items and the capacity change names, but the table is the same.

Press Play on a diagram to walk through it one step at a time.

CompareKnapsack variants with a 1D table
0/1 knapsack
  • Each item once
  • Loop capacity downwards
  • dp[c] = max(dp[c], dp[c-w] + v)
Unbounded knapsack
  • Items reusable
  • Loop capacity upwards
  • Coin change is this form
Flow1D 0/1 knapsack: items (1,1), (3,4), (4,5), W = 7
  1. 1
    Start

    dp = [0, 0, 0, 0, 0, 0, 0, 0]

  2. 2
    Item (1, 1)

    dp = [0, 1, 1, 1, 1, 1, 1, 1]

  3. 3
    Item (3, 4)

    dp = [0, 1, 1, 4, 5, 5, 5, 5]

  4. 4
    Item (4, 5)

    dp = [0, 1, 1, 4, 5, 6, 6, 9]

  5. 5
    Answer

    dp[7] = 9: items 2 and 3

In depth

Start with the 2D table

The clearest form is dp[i][c] = the best value using only the first i items with capacity c. Row 0 (no items) is all zeros. For item i with weight w and value v, dp[i][c] = dp[i - 1][c] if you skip it, or dp[i - 1][c - w] + v if you take it and c >= w. The answer is dp[n][W].

There are (n + 1) x (W + 1) cells, each O(1), so time is O(n x W). The 2D table is also what lets you rebuild the chosen items: if dp[i][c] differs from dp[i - 1][c], item i was taken, so subtract its weight and move up a row.

Every row only reads the row directly above it. That observation leads to the one-row version.

MapTwo choices for dp[i][c]
dp[i][c]: first i items, capacity c
  • Skip item i
    • dp[i-1][c]
  • Take item i (if w <= c)
    • dp[i-1][c - w] + v

Why the 1D loop runs backwards

With one row, dp[c] = max(dp[c], dp[c - w] + v). The right side must still hold the old row's values. Looping c from W down to w guarantees that: dp[c - w] is to the left of c and has not been touched yet in this item's pass.

Loop forwards and dp[c - w] may already include the current item, so the same item is taken twice. Try one item of weight 2 and value 3 with W = 4. Forwards: dp[2] = 3, then dp[4] = dp[2] + 3 = 6, using the item twice. Backwards: dp[4] = dp[2] + 3 = 0 + 3 = 3, then dp[2] = 3. Correct.

That bug is exactly the unbounded knapsack, where items can be reused. So the loop direction is the whole difference between the two problems.

CompareOne item (w 2, v 3), W = 4
Backwards (0/1)
  • c = 4: dp[2] is still 0, so 3
  • c = 3: 3
  • c = 2: 3
  • Final dp[4] = 3
Forwards (unbounded)
  • c = 2: 3
  • c = 3: 3
  • c = 4: dp[2] is already 3, so 6
  • Final dp[4] = 6

Coin change: combinations versus orderings

Counting ways to make an amount with unlimited coins is an unbounded knapsack where values are replaced by counts: ways[c] += ways[c - coin], with ways[0] = 1. The loop order now changes the meaning.

Coins in the outer loop, amounts inside: each coin is added in a fixed order, so 1 + 2 and 2 + 1 count once. That counts combinations. For coins [1, 2, 5] and amount 5 it gives 4. Amounts in the outer loop, coins inside: every last coin is tried at every amount, so different orders count separately. That counts sequences. For [1, 2, 3] and target 4 it gives 7.

The fewest-coins version uses min instead of +, and either loop order works because the minimum does not care about order.

  • Combinations: for coin, then for amount
  • Orderings: for amount, then for coin
  • Fewest coins: min, any order

Subset sum, partition and target sum

Subset sum asks whether some items add up to exactly T. It is 0/1 knapsack with True/False: can[c] = can[c] or can[c - x], looping backwards. Equal partition is subset sum with T = total / 2, and an odd total is an instant no.

Target sum assigns + or - to every number to reach a target S. If P is the sum of the plus group, then P - (total - P) = S, so P = (total + S) / 2. Now count subsets with sum P. If (total + S) is odd or negative, the answer is 0.

Python has a neat trick for subset sum: store reachable sums as bits of one big integer. Start with bits = 1 (sum 0 reachable) and for each x do bits |= bits << x. Then sum T is reachable when bits >> T & 1 is 1. Python's big integers do the shifting in machine words, so this runs many times faster than a list loop.

When the capacity is huge

Knapsack is NP-hard: no known algorithm is polynomial in the input size. O(n x W) looks polynomial, but W is a number, and writing W takes only about log2(W) bits. Doubling the number of digits squares the work. That is what pseudo-polynomial means.

If W is 10^9 but values are small, flip the table: dp[v] = the minimum weight needed to reach value exactly v, then take the largest v with dp[v] <= W. That costs O(n x total value). If n is at most about 40, meet in the middle works: list all subset sums of each half (2^20 each, about a million), sort one list, and binary search it for each sum from the other.

  • NP-hard in general
  • Small values: DP over value instead of weight
  • n up to about 40: meet in the middle

Learn it in 4 short steps

About 55m each. Track them with a timer in your plan.

  1. 1
    Define the 0/1 knapsack state~55m
  2. 2
    Iterate capacity backwards for 1D DP~55m
  3. 3
    Solve unbounded knapsack and coin change~55m
  4. 4
    Solve subset sum and partition~55m

Key points

  • Time O(n x W), space O(W) with a 1D table.
  • It is pseudo-polynomial: fast only when capacity W is small.
  • Subset sum: boolean dp[c] meaning sum c is reachable.
  • Iterating capacity downwards prevents reusing an item in the same row.

Key terms

Tap a card to flip it. 0/3 known

Examples

python
def knapsack(items, W):           # items = [(weight, value)], O(n * W)
    dp = [0] * (W + 1)
    for w, v in items:
        for c in range(W, w - 1, -1):     # downwards: each item once
            dp[c] = max(dp[c], dp[c - w] + v)
    return dp[W]

def coin_change(coins, amount):   # unbounded, fewest coins
    INF = float('inf')
    dp = [0] + [INF] * amount
    for c in range(1, amount + 1):
        dp[c] = min((dp[c - x] + 1 for x in coins if x <= c), default=INF)
    return dp[amount] if dp[amount] < INF else -1

Which items were packed?

Same items as the diagram: weights 1, 3, 4 and values 1, 4, 5, capacity 7. Step 1: fill the 2D table. Step 2: start at dp[3][7] = 9. It differs from dp[2][7] = 5, so item 3 was taken; capacity becomes 7 - 4 = 3. Step 3: dp[2][3] = 4 differs from dp[1][3] = 1, so item 2 was taken; capacity becomes 0. Step 4: dp[1][0] equals dp[0][0], so item 1 was skipped.

python
def knapsack_items(items, W):         # items = [(weight, value)]
    n = len(items)
    dp = [[0] * (W + 1) for _ in range(n + 1)]
    for i, (w, v) in enumerate(items, 1):
        for c in range(W + 1):
            dp[i][c] = dp[i - 1][c]
            if w <= c:
                dp[i][c] = max(dp[i][c], dp[i - 1][c - w] + v)
    chosen, c = [], W
    for i in range(n, 0, -1):
        if dp[i][c] != dp[i - 1][c]:
            chosen.append(i - 1); c -= items[i - 1][0]
    return dp[n][W], chosen[::-1]

print(knapsack_items([(1, 1), (3, 4), (4, 5)], 7))  # (9, [1, 2])

Same coins, two different counts

With coins [1, 2, 5] and amount 5, the combinations are 5, 2+2+1, 2+1+1+1 and 1+1+1+1+1: four. If order matters, 2+2+1, 2+1+2 and 1+2+2 are all different, and the count is 9. The two functions below differ only in which loop is outside.

python
def combinations(coins, amount):      # order does not matter
    ways = [1] + [0] * amount
    for coin in coins:
        for c in range(coin, amount + 1):
            ways[c] += ways[c - coin]
    return ways[amount]

def orderings(coins, amount):         # order matters
    ways = [1] + [0] * amount
    for c in range(1, amount + 1):
        ways[c] = sum(ways[c - coin] for coin in coins if coin <= c)
    return ways[amount]

print(combinations([1, 2, 5], 5), orderings([1, 2, 5], 5))  # 4 9

Quick reference

  • 0/1 knapsack: for item, for c from W down to w: dp[c] = max(dp[c], dp[c - w] + v)
  • Unbounded knapsack: the same line with c looping upwards
  • Time O(n x W), space O(W): pseudo-polynomial
  • Count combinations: coins outer loop; count orderings: amount outer loop
  • Equal partition: subset sum to total / 2; odd total means False
  • Target sum with +/-: count subsets with sum (total + S) / 2
  • Python subset-sum trick: bits |= bits << x, then test bits >> T & 1
  • Need the chosen items? Keep the 2D table and walk back from dp[n][W]

Common mistakes

  • Looping capacity upwards in 0/1 knapsack, which reuses items.
  • Assuming knapsack is fast for capacities in the billions.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1In 1D 0/1 knapsack, what goes wrong if the capacity loop runs upwards?

Question 2

2Coins [1, 2] and amount 3. How many ways if order does not matter, and if it does?

Question 3

3Why is O(n x W) called pseudo-polynomial?

Question 4

4Numbers [1, 1, 1, 1, 1], target sum 3 using + and -. Which subset sum do you count?

Question 5

5n = 100 items, W = 10^9, every value at most 100. Which approach fits?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Return True if nums can be split into two groups with equal sums. Examples: [1, 5, 11, 5] is True, [1, 2, 3, 5] is False.

  2. Exercise 2medium

    Put + or - in front of every number so the total equals target. Count the ways. Example: [1, 1, 1, 1, 1], target 3 gives 5.

  3. Exercise 3hard

    Each string is made of 0s and 1s. Pick the largest number of strings using at most m zeros and n ones in total. Example: ["10", "0001", "111001", "1", "0"], m = 5, n = 3 gives 4.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between 0/1 and unbounded knapsack?
In 0/1 knapsack each item can be used once; in unbounded knapsack items can be reused without limit. In the 1D code, the only change is whether the capacity loop runs down or up.
Why does greedy not work for 0/1 knapsack?
Taking the best value per weight first can leave space you cannot fill. Greedy is only correct for fractional knapsack, where you may take part of an item.
Is coin change a knapsack problem?
Yes, it is an unbounded knapsack: coins are reusable items and the amount is the capacity. Fewest coins uses min, and counting ways uses addition.
How big can W be for knapsack DP in Python?
Roughly n x W up to about 10^7 simple steps runs in a few seconds. Beyond that, use the bitset trick for subset sum, NumPy, or a different formulation.

Go deeper

ShareXLinkedInWhatsApp