Knapsack, Subset Sum & Coin Change
Choosing items under a budget.
With 100 items there are subsets to choose from, far beyond any computer. Yet if the weights are integers and the bag holds , 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 , is the reason knapsack is still NP-hard.
What you’ll learn
- Define the state of the 0/1 knapsack problem, prove its recurrence, and fill the table in 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 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 items, item with an integer weight and a value , and a bag of capacity . Choose a subset of total weight at most whose total value is as large as possible. Each item is taken whole or not at all.
The brute force tries all subsets, time. Its waste: once the first 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.
Base case. With no items the only subset is the empty one, worth 0, whatever the capacity.
Item left out. A subset of the first items that avoids item is exactly a subset of the first items, under the same capacity. The best of them is worth
Item taken (possible only if ). Remove it, and the rest is a subset of the first items of weight at most ; conversely, adding item to any such subset gives a feasible choice. So the best subset containing it is worth
Every subset falls in one of the two cases, so is the larger of the two values. Each cell reads only row , so filling rows in order is valid, and each cell costs :
One array, and why the loop runs downward
Row reads only row , so one array of 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.
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 Dtime and 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 : 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, with reuse allowed. The direction of one loop encodes how many copies of each item exist.
In the bounded knapsack item is available times. Treating it as separate 0/1 items costs . Bundling copies in powers of two is much cheaper:
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 bundleBundles of copies make every count from to , and the final bundle adds every count from to . Together they make exactly the counts , and never more than .
| Variant | 1-D loop over capacity | Time (worst case) |
|---|---|---|
| 0/1: each item at most once | downward | |
| Unbounded: unlimited copies | upward | |
| Bounded, item as separate copies | downward, once per copy | |
| Bounded, binary bundles | downward, once per bundle | |
| Bounded, sliding-window maximum per residue mod | a monotonic queue |
A shop sells each of products in unlimited quantity. You want the largest total value within a budget , and you keep a single array . How should the capacity loop run inside the loop over products?
- Downward, from to
- Upward, from to
- Either direction gives the same result
- One array cannot work; you need the full table
Show the answer
B. Upward, from to
Upward, 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 and a target , and you ask whether some subset sums to exactly . It is knapsack with Booleans: is true when some subset of the first numbers sums to , and
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 ". A machine word holds bits, so one shift-or handles 64 cells at once (word parallelism): word operations instead of .
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 FalsePython'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.
| Problem | Reduction to subset sum |
|---|---|
| Split the numbers into two groups with equal sums | Total must be even; ask for a subset with sum |
| Split them into two groups with sums as close as possible | Take the largest reachable ; the difference is |
| Put or before each number to reach ; count the ways | Count the subsets with sum (zero ways if is odd or ) |
| Choose exactly numbers with sum | Add the count to the state: , |
Let be the sum of the numbers that get a plus sign and the sum of those that get a minus sign. Every number gets exactly one sign, so
Adding the two equations fixes . Choosing signs is the same as choosing the plus-subset, so the number of sign patterns equals the number of subsets with this sum:
Count them with the same downward loop, adding instead of maximizing:
ways[s] += ways[s - x]for from down to , starting fromways[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 (keeping their order) so that the total is ? The two 1s are different positions.
Three. and , so the plus-signed numbers must sum to . The subsets with sum 4 are , and , giving the patterns , and .
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 exactly: and , where runs over the denominations and marks amounts that cannot be paid. With coins and the table is : two coins, , while "largest coin first" pays , three coins.
The number of ways to pay . Here the order of the two loops decides what is counted.
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 9Both run in time for denominations. The four combinations of 6 are , , and ; as ordered sequences there are 9.
Coins outside. Invariant: after the passes for the first denominations, is the number of multisets of those denominations with sum . The pass for coin splits each multiset by whether it uses ; one that does is a multiset for (which may use again, hence the upward loop) plus one more :
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.
Amounts outside. Every ordered sequence with sum ends with some coin , and removing it leaves a sequence with sum . Different last coins give different sequences, so this sum counts sequences, not multisets:
You climb a staircase of 5 steps, taking 1 or 2 steps at a time, and the order of your moves matters ( and are different climbs). Which computation counts the climbs?
- Step sizes in the outer loop, amounts inside: it returns 3
- Amounts in the outer loop, step sizes inside: it returns 8
- Either loop order: both return 8
- 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: , the Fibonacci recurrence, which gives 1, 2, 3, 5, 8 for . With the step sizes outside you would count only the 3 multisets , and .
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: , or up to about –, with within a few times simple steps (the rule of thumb for 1–2 seconds in a compiled language).
- The question is a maximum value, a yes/no "exactly ", the fewest items, or "how many ways, modulo ".
- "Split into two groups" with equal or closest sums: subset sum to .
| Problem (in brief) | Key idea | Cost |
|---|---|---|
| Pack items under a weight limit, each at most once, maximizing value | , capacity loop downward | |
| Split numbers into two groups whose sums are as close as possible | Bitset of reachable sums; the largest | |
| Fewest coins to pay an amount, unlimited supply | ||
| Number of ways to pay an amount, order irrelevant | Coins outside, amounts inside, upward | |
| Signs before each number to hit a target; count the ways | Count the subsets with sum |
You get integers, each up to , and a target : does some subset sum to exactly ? Which approach fits a 1-second limit?
- A bitset of reachable sums up to
- Meet in the middle: all subset sums of each half, then match pairs
- Greedy: take the largest numbers that still fit
- 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 subset sums; sort one list and look up for every sum of the other, about steps. A table over sums would need up to columns.
Key takeaways
- 0/1 knapsack: , time, and 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 binary bundles.
- Subset sum is knapsack with Booleans, with a bitset; equal partitions and target sums reduce to it through .
- Coin change: the fewest coins is an unbounded DP; for counting, coins outside counts combinations and amounts outside counts ordered sequences.
- 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.
In the one-array 0/1 knapsack code, the capacity loop is changed to run upward, from to . What does the code now return?
- The same optimum, more slowly
- The optimum of the unbounded knapsack, where every item may be used any number of times
- A value that can be smaller than the 0/1 optimum
- An index error, because becomes negative
Show the answer
B. The optimum of the unbounded knapsack, where every item may be used any number of times
Upward, 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.
This code runs with coins and amount : 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]?
- 3
- 4
- 5
- 8
Show the answer
C. 5
With the amount in the outer loop, 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 , , .
Knapsack is NP-hard, yet the table solves it in time. Why is this not a polynomial-time algorithm?
- Because hides a large constant factor
- Because is written with about bits, so can be exponential in the length of the input
- Because the table needs memory
- It is polynomial; it only shows that P = NP for knapsack instances
Show the answer
B. Because is written with about bits, so can be exponential in the length of the input
Polynomial time is measured in the number of bits of the input. A capacity of takes 61 bits to write, but the table has columns. The algorithm is pseudo-polynomial: polynomial in the numeric value , not in its length.
You have items with weights up to , values that are integers from 1 to 100, and capacity . Which approach fits?
- The usual table over capacities
- A table over total values: for each value , the least weight that achieves it
- Greedy by value per weight
- Brute force over all subsets
Show the answer
B. A table over total values: for each value , the least weight that achieves it
Total values are at most , so a table indexed by value has about cells; the answer is the largest whose least weight is at most . The capacity table would need cells.
Go deeper
- Pseudo-Polynomial Time · Why O(nW) is not polynomial, and weak versus strong NP-hardness.
- Approximating Knapsack · Rounding values into a fully polynomial-time approximation scheme.
- Subset Sum, Faster · Bitset DP, and near-linear pseudo-polynomial algorithms.
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).