Simple Algorithm
Algorithms & Data Structures · Optimized · 24 min

Knapsack, Subset Sum & Coin Change

Choosing items under a budget.

With 100 items there are 2100≈1.3×10302^{100}\approx1.3\times10^{30} subsets to choose from, far beyond any computer. Yet if the weights are integers and the bag holds W=104W=10^4, a table of about a million numbers finds the best subset in a blink. That table is this lesson, and its one weakness, the size of WW, is the reason knapsack is still NP-hard.

What you’ll learn

  • Define the state (i,c)(i,c) of the 0/1 knapsack problem, prove its recurrence, and fill the table in Θ(nW)\Theta(nW) time.
  • Compress the table to one array, explain why the capacity loop runs downward for 0/1 items and upward for unlimited ones, and handle bounded counts with O(log⁡c)O(\log c) bundles.
  • Solve subset sum with a bitset, and reduce equal partitions and signed target sums to it.
  • Compute the fewest coins for an amount, and count payments as combinations or as ordered sequences by choosing the loop order.
  • Recognize knapsack-shaped problems from their constraints, and tell them apart from look-alikes that need meet in the middle, a greedy rule or a different state.

From 2ⁿ subsets to an n × W table

In the 0/1 knapsack problem you have nn items, item ii with an integer weight wi≥1w_i\ge1 and a value vi≥0v_i\ge0, and a bag of capacity WW. Choose a subset of total weight at most WW whose total value is as large as possible. Each item is taken whole or not at all.

The brute force tries all 2n2^n subsets, O(2nn)O(2^n n) time. Its waste: once the first ii items are decided, the remaining decisions care about only one number, the capacity that is left. Many different partial choices leave the same capacity, and the brute force solves the same remaining problem again for each of them.

best(i,c)={best(i−1,c)if wi−1>c,max⁡(best(i−1,c), best(i−1,c−wi−1)+vi−1)otherwise,best(0,c)=0\mathrm{best}(i,c)=\begin{cases}\mathrm{best}(i-1,c) & \text{if } w_{i-1}>c,\\[2pt] \max\big(\mathrm{best}(i-1,c),\ \mathrm{best}(i-1,c-w_{i-1})+v_{i-1}\big) & \text{otherwise,}\end{cases}\qquad \mathrm{best}(0,c)=0
Item i−1i-1 is either left out or taken, and taking it uses wi−1w_{i-1} units of the capacity.
DerivationWhy the recurrence is right
  1. best(0,c)=0(0≤c≤W)\mathrm{best}(0,c)=0\qquad(0\le c\le W)

    Base case. With no items the only subset is the empty one, worth 0, whatever the capacity.

  2. best(i−1,c)\mathrm{best}(i-1,c)

    Item i−1i-1 left out. A subset of the first ii items that avoids item i−1i-1 is exactly a subset of the first i−1i-1 items, under the same capacity. The best of them is worth

  3. best(i−1,c−wi−1)+vi−1\mathrm{best}(i-1,c-w_{i-1})+v_{i-1}

    Item i−1i-1 taken (possible only if wi−1≤cw_{i-1}\le c). Remove it, and the rest is a subset of the first i−1i-1 items of weight at most c−wi−1c-w_{i-1}; conversely, adding item i−1i-1 to any such subset gives a feasible choice. So the best subset containing it is worth

  4. T=Θ(nW) time,Θ(nW) space (Θ(W) in the next step)T=\Theta(nW)\ \text{time},\qquad \Theta(nW)\ \text{space (}\Theta(W)\text{ in the next step)}

    Every subset falls in one of the two cases, so best(i,c)\mathrm{best}(i,c) is the larger of the two values. Each cell reads only row i−1i-1, so filling rows i=1,2,…,ni=1,2,\dots,n in order is valid, and each cell costs O(1)O(1):

One array, and why the loop runs downward

Row ii reads only row i−1i-1, so one array of W+1W+1 numbers is enough: process the items one at a time and overwrite the array in place. The whole subtlety is the direction of the capacity loop.

python
def knapsack_01(weights, values, W):
    best = [0] * (W + 1)                 # best[c]: best value with capacity c
    for w, v in zip(weights, values):
        for c in range(W, w - 1, -1):    # downward: best[c - w] is still the old row
            best[c] = max(best[c], best[c - w] + v)
    return best[W]

print(knapsack_01([2, 3, 4, 5], [3, 5, 7, 8], 8))   # 13: items B and D

Θ(nW)\Theta(nW) time and Θ(W)\Theta(W) space. The earlier rows are gone, so recovering which items were taken needs the full table, or the techniques of Reconstructing Solutions & Saving Space.

The bug is easy to see on the example. With the upward loop, the array after item A alone is [0,0,3,3,6,6,9,9,12][0,0,3,3,6,6,9,9,12]: capacity 8 is "worth" 12, which is four copies of A. After all four items the upward loop returns 14, two copies of C, instead of 13.

That wrong answer is the right answer to another problem. In the unbounded knapsack every item comes in unlimited supply, and the upward loop is exactly its recurrence, best(c)=max⁡(best(c), best(c−w)+v)\mathrm{best}(c)=\max\big(\mathrm{best}(c),\ \mathrm{best}(c-w)+v\big) with reuse allowed. The direction of one loop encodes how many copies of each item exist.

In the bounded knapsack item ii is available cic_i times. Treating it as cic_i separate 0/1 items costs Θ(W∑ci)\Theta(W\sum c_i). Bundling copies in powers of two is much cheaper:

python
def bundles(w, v, count):
    """count copies of one item -> O(log count) bundles, each used as a 0/1 item."""
    out, k = [], 1
    while count > 0:
        take = min(k, count)             # 1, 2, 4, ... copies, then the remainder
        out.append((take * w, take * v))
        count -= take
        k *= 2
    return out

print([bw // 2 for bw, bv in bundles(2, 3, 13)])   # [1, 2, 4, 6] copies per bundle

Bundles of 1,2,…,2k−11,2,\dots,2^{k-1} copies make every count from 00 to 2k−12^k-1, and the final bundle r≤2kr\le2^k adds every count from rr to cc. Together they make exactly the counts 0,…,c0,\dots,c, and never more than cc.

Variant1-D loop over capacityTime (worst case)
0/1: each item at most oncedownwardΘ(nW)\Theta(nW)
Unbounded: unlimited copiesupwardΘ(nW)\Theta(nW)
Bounded, item ii as cic_i separate copiesdownward, once per copyΘ(W∑ici)\Theta(W\sum_i c_i)
Bounded, binary bundlesdownward, once per bundleΘ(W∑ilog⁡ci)\Theta(W\sum_i\log c_i)
Bounded, sliding-window maximum per residue mod wiw_ia monotonic queueΘ(nW)\Theta(nW)
The last row is developed in Monotonic Queues in Dynamic Programming.
Check your understanding

A shop sells each of nn products in unlimited quantity. You want the largest total value within a budget WW, and you keep a single array best[0..W]\mathrm{best}[0..W]. How should the capacity loop run inside the loop over products?

  1. Downward, from WW to ww
  2. Upward, from ww to WW
  3. Either direction gives the same result
  4. One array cannot work; you need the full n×Wn\times W table
Show the answer

B. Upward, from ww to WW

Upward, best[c−w]\mathrm{best}[c-w] has already been updated for this product, so it may already contain copies of it, and adding one more is allowed: that is the unbounded recurrence. Downward would allow each product at most once.

Subset sum, partitions and signs

In subset sum you are given positive integers a0,…,an−1a_0,\dots,a_{n-1} and a target tt, and you ask whether some subset sums to exactly tt. It is knapsack with Booleans: reachi[s]\mathrm{reach}_i[s] is true when some subset of the first ii numbers sums to ss, and

reachi[s]=reachi−1[s] ∨ reachi−1[s−ai−1],reach0[s]=[s=0].\mathrm{reach}_i[s]=\mathrm{reach}_{i-1}[s]\ \lor\ \mathrm{reach}_{i-1}[s-a_{i-1}],\qquad \mathrm{reach}_0[s]=[s=0].

A whole row of Booleans is a row of bits, and the update is "OR the row with a copy of itself shifted left by ai−1a_{i-1}". A machine word holds w=64w=64 bits, so one shift-or handles 64 cells at once (word parallelism): O(nt/w)O(nt/w) word operations instead of O(nt)O(nt).

python
def subset_sum(a, t):
    reach = 1                            # bit s set <=> some subset sums to s
    mask = (1 << (t + 1)) - 1            # keep only the sums 0..t
    for x in a:
        reach = (reach | (reach << x)) & mask
    return reach >> t & 1 == 1

print(subset_sum([2, 3, 7], 12), subset_sum([2, 3, 7], 11))   # True False

Python's integers are arbitrary-size bitsets. In C++, std::bitset<T + 1> reach; reach[0] = 1; for (int x : a) reach |= reach << x; does the same with a compile-time size.

ProblemReduction to subset sum
Split the numbers into two groups with equal sumsTotal SS must be even; ask for a subset with sum S/2S/2
Split them into two groups with sums as close as possibleTake the largest reachable s≤S/2s\le S/2; the difference is S−2sS-2s
Put ++ or −- before each number to reach TT; count the waysCount the subsets with sum (S+T)/2(S+T)/2 (zero ways if S+TS+T is odd or ∣T∣>S\abs{T}>S)
Choose exactly kk numbers with sum ttAdd the count to the state: reach[j][s]\mathrm{reach}[j][s], O(nkt)O(nkt)
Equal partition of [3,1,4,2,2][3,1,4,2,2]: S=12S=12, and 6=4+26=4+2 is reachable, so the answer is yes.
DerivationSigns become a subset
  1. P+N=S,P−N=TP+N=S,\qquad P-N=T

    Let PP be the sum of the numbers that get a plus sign and NN the sum of those that get a minus sign. Every number gets exactly one sign, so

  2. P=S+T2P=\frac{S+T}{2}

    Adding the two equations fixes PP. Choosing signs is the same as choosing the plus-subset, so the number of sign patterns equals the number of subsets with this sum:

  3. waysi[s]=waysi−1[s]+waysi−1[s−ai−1]\mathrm{ways}_i[s]=\mathrm{ways}_{i-1}[s]+\mathrm{ways}_{i-1}[s-a_{i-1}]

    Count them with the same downward loop, adding instead of maximizing: ways[s] += ways[s - x] for ss from PP down to xx, starting from ways[0] = 1. Counts grow fast, so contests ask for them modulo a prime.

Think first In how many ways can you put ++ or −- before each of the numbers 2,1,3,12,1,3,1 (keeping their order) so that the total is 11? The two 1s are different positions.

Three. S=7S=7 and T=1T=1, so the plus-signed numbers must sum to P=(7+1)/2=4P=(7+1)/2=4. The subsets with sum 4 are {3,first 1}\{3,\text{first }1\}, {3,second 1}\{3,\text{second }1\} and {2,1,1}\{2,1,1\}, giving the patterns −2+1+3−1-2+1+3-1, −2−1+3+1-2-1+3+1 and +2+1−3+1+2+1-3+1.

Coin change: fewest coins, and counting payments

In coin change each denomination comes in unlimited supply, so it is an unbounded knapsack. Two questions are asked about it.

The fewest coins that pay an amount AA exactly: fewest[0]=0\mathrm{fewest}[0]=0 and fewest[a]=1+min⁡c≤afewest[a−c]\mathrm{fewest}[a]=1+\min_{c\le a}\mathrm{fewest}[a-c], where cc runs over the denominations and ∞\infty marks amounts that cannot be paid. With coins {1,3,4}\{1,3,4\} and A=6A=6 the table is 0,1,2,1,1,2,20,1,2,1,1,2,2: two coins, 3+33+3, while "largest coin first" pays 4+1+14+1+1, three coins.

The number of ways to pay AA. Here the order of the two loops decides what is counted.

python
def count_combinations(coins, A):
    ways = [1] + [0] * A                 # ways[0] = 1: the empty payment
    for c in coins:                      # coins outside: each multiset once
        for a in range(c, A + 1):        # upward: coin c may repeat
            ways[a] += ways[a - c]
    return ways[A]

def count_sequences(coins, A):
    ways = [1] + [0] * A
    for a in range(1, A + 1):            # amounts outside: orders count
        for c in coins:
            if c <= a:
                ways[a] += ways[a - c]   # classify by the last coin
    return ways[A]

print(count_combinations([1, 3, 4], 6), count_sequences([1, 3, 4], 6))   # 4 9

Both run in Θ(kA)\Theta(kA) time for kk denominations. The four combinations of 6 are 1+1+1+1+1+11{+}1{+}1{+}1{+}1{+}1, 1+1+1+31{+}1{+}1{+}3, 1+1+41{+}1{+}4 and 3+33{+}3; as ordered sequences there are 9.

DerivationWhy the loop order decides what is counted
  1. waysj[a]=waysj−1[a]+waysj[a−cj]\mathrm{ways}_j[a]=\mathrm{ways}_{j-1}[a]+\mathrm{ways}_j[a-c_j]

    Coins outside. Invariant: after the passes for the first jj denominations, ways[a]\mathrm{ways}[a] is the number of multisets of those denominations with sum aa. The pass for coin cjc_j splits each multiset by whether it uses cjc_j; one that does is a multiset for a−cja-c_j (which may use cjc_j again, hence the upward loop) plus one more cjc_j:

  2. {1,1,4} is counted once, as 1+1+4, never as 4+1+1\{1,1,4\}\ \text{is counted once, as }1{+}1{+}4\text{, never as }4{+}1{+}1

    Every multiset is built in one fixed order, all copies of the first coin, then all copies of the second, and so on, so it is counted exactly once.

  3. seq[a]=∑c≤aseq[a−c],seq[0]=1\mathrm{seq}[a]=\sum_{c\le a}\mathrm{seq}[a-c],\qquad \mathrm{seq}[0]=1

    Amounts outside. Every ordered sequence with sum aa ends with some coin cc, and removing it leaves a sequence with sum a−ca-c. Different last coins give different sequences, so this sum counts sequences, not multisets:

Check your understanding

You climb a staircase of 5 steps, taking 1 or 2 steps at a time, and the order of your moves matters (1+2+21{+}2{+}2 and 2+1+22{+}1{+}2 are different climbs). Which computation counts the climbs?

  1. Step sizes {1,2}\{1,2\} in the outer loop, amounts inside: it returns 3
  2. Amounts in the outer loop, step sizes inside: it returns 8
  3. Either loop order: both return 8
  4. The fewest-coins table: it returns 3
Show the answer

B. Amounts in the outer loop, step sizes inside: it returns 8

Ordered climbs are classified by their last move: seq[a]=seq[a−1]+seq[a−2]\mathrm{seq}[a]=\mathrm{seq}[a-1]+\mathrm{seq}[a-2], the Fibonacci recurrence, which gives 1, 2, 3, 5, 8 for a=1,…,5a=1,\dots,5. With the step sizes outside you would count only the 3 multisets {1,1,1,1,1}\{1,1,1,1,1\}, {1,1,1,2}\{1,1,1,2\} and {1,2,2}\{1,2,2\}.

Recognizing it

Reach for a knapsack-style table when you see these signals:

  • Choose a subset (or a multiset) of items, each with an integer size (weight, cost, coin value, length), under a budget or toward an exact total.
  • The sizes or the budget are small integers: WW, tt or AA up to about 10510^5–10610^6, with n⋅Wn\cdot W within a few times 10810^8 simple steps (the rule of thumb for 1–2 seconds in a compiled language).
  • The question is a maximum value, a yes/no "exactly tt", the fewest items, or "how many ways, modulo 109+710^9+7".
  • "Split into two groups" with equal or closest sums: subset sum to S/2S/2.
Problem (in brief)Key ideaCost
Pack items under a weight limit, each at most once, maximizing valuebest[c]\mathrm{best}[c], capacity loop downwardΘ(nW)\Theta(nW)
Split numbers into two groups whose sums are as close as possibleBitset of reachable sums; the largest s≤S/2s\le S/2O(nS/w)O(nS/w)
Fewest coins to pay an amount, unlimited supplyfewest[a]=1+min⁡cfewest[a−c]\mathrm{fewest}[a]=1+\min_c\mathrm{fewest}[a-c]Θ(kA)\Theta(kA)
Number of ways to pay an amount, order irrelevantCoins outside, amounts inside, upwardΘ(kA)\Theta(kA)
Signs before each number to hit a target; count the waysCount the subsets with sum (S+T)/2(S+T)/2Θ(nS)\Theta(nS)
Five common shapes. SS is the sum of all the numbers, kk the number of denominations, w=64w=64 the word size.
Check your understanding

You get n=36n=36 integers, each up to 101210^{12}, and a target tt: does some subset sum to exactly tt? Which approach fits a 1-second limit?

  1. A bitset of reachable sums up to tt
  2. Meet in the middle: all subset sums of each half, then match pairs
  3. Greedy: take the largest numbers that still fit
  4. A table indexed by the number of items chosen
Show the answer

B. Meet in the middle: all subset sums of each half, then match pairs

Each half has 218=262,1442^{18}=262{,}144 subset sums; sort one list and look up t−st-s for every sum ss of the other, about 218⋅18≈5×1062^{18}\cdot18\approx5\times10^6 steps. A table over sums would need up to 3.6×10133.6\times10^{13} columns.

Key takeaways

  • 0/1 knapsack: best(i,c)=max⁡(best(i−1,c), best(i−1,c−wi−1)+vi−1)\mathrm{best}(i,c)=\max\big(\mathrm{best}(i-1,c),\ \mathrm{best}(i-1,c-w_{i-1})+v_{i-1}\big), Θ(nW)\Theta(nW) time, and Θ(W)\Theta(W) space with one array.
  • The capacity loop's direction encodes multiplicity: downward means each item at most once, upward means unlimited copies; bounded counts become O(log⁡c)O(\log c) binary bundles.
  • Subset sum is knapsack with Booleans, O(nt/w)O(nt/w) with a bitset; equal partitions and ±\pm target sums reduce to it through P=(S+T)/2P=(S+T)/2.
  • Coin change: the fewest coins is an unbounded DP; for counting, coins outside counts combinations and amounts outside counts ordered sequences.
  • Θ(nW)\Theta(nW) is pseudo-polynomial: fast when the numbers are small, useless when they are huge, where meet in the middle, a table over values or approximation take over.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In the one-array 0/1 knapsack code, the capacity loop is changed to run upward, from ww to WW. What does the code now return?

  1. The same optimum, more slowly
  2. The optimum of the unbounded knapsack, where every item may be used any number of times
  3. A value that can be smaller than the 0/1 optimum
  4. An index error, because c−wc-w becomes negative
Show the answer

B. The optimum of the unbounded knapsack, where every item may be used any number of times

Upward, best[c−w]\mathrm{best}[c-w] has already been updated with the current item, so the item can be added again and again: that is exactly the unbounded recurrence. On the lesson's items it returns 14 (two copies of C) instead of 13.

Question 2

This code runs with coins {1,2}\{1,2\} and amount A=4A=4: ways = [1] + [0] * A, then for a in range(1, A + 1): for c in coins: if c <= a: ways[a] += ways[a - c]. What is ways[4]?

  1. 3
  2. 4
  3. 5
  4. 8
Show the answer

C. 5

With the amount in the outer loop, ways[a]=∑cways[a−c]\mathrm{ways}[a]=\sum_c\mathrm{ways}[a-c] counts ordered sequences by their last coin: 1111, 112, 121, 211 and 22, five of them. Putting the coins in the outer loop would count the 3 combinations {1,1,1,1}\{1,1,1,1\}, {1,1,2}\{1,1,2\}, {2,2}\{2,2\}.

Question 3

Knapsack is NP-hard, yet the table solves it in Θ(nW)\Theta(nW) time. Why is this not a polynomial-time algorithm?

  1. Because Θ(nW)\Theta(nW) hides a large constant factor
  2. Because WW is written with about log⁡2W\log_2 W bits, so nWnW can be exponential in the length of the input
  3. Because the table needs Θ(nW)\Theta(nW) memory
  4. It is polynomial; it only shows that P = NP for knapsack instances
Show the answer

B. Because WW is written with about log⁡2W\log_2 W bits, so nWnW can be exponential in the length of the input

Polynomial time is measured in the number of bits of the input. A capacity of 2602^{60} takes 61 bits to write, but the table has 260+12^{60}+1 columns. The algorithm is pseudo-polynomial: polynomial in the numeric value WW, not in its length.

Question 4

You have n=50n=50 items with weights up to 10910^9, values that are integers from 1 to 100, and capacity W=109W=10^9. Which approach fits?

  1. The usual table over capacities 0..W0..W
  2. A table over total values: for each value q≤5000q\le5000, the least weight that achieves it
  3. Greedy by value per weight
  4. Brute force over all subsets
Show the answer

B. A table over total values: for each value q≤5000q\le5000, the least weight that achieves it

Total values are at most 50⋅100=500050\cdot100=5000, so a table indexed by value has about 50×5001≈2.5×10550\times5001\approx2.5\times10^5 cells; the answer is the largest qq whose least weight is at most WW. The capacity table would need 5×10105\times10^{10} cells.

Go deeper

Further reading

  • J. Kleinberg & É. Tardos, Algorithm Design (Pearson, 2005), §6.4, "Subset Sums and Knapsacks: Adding a Variable".
  • S. Dasgupta, C. H. Papadimitriou & U. V. Vazirani, Algorithms (McGraw-Hill, 2006), §6.4, "Knapsack".
  • H. Kellerer, U. Pferschy & D. Pisinger, Knapsack Problems (Springer, 2004).
  • A. Laaksonen, Competitive Programmer's Handbook (2018), chapter 7: the coin problem and knapsack problems (free online).