0/1 Knapsack and Pseudo-Polynomial Time
A hiker can carry at most kilograms. Each of items has a weight and a value, and each is either packed whole or left behind. Which items should go in? This is the 0/1 knapsack problem, and its DP is one of the most used in practice: budgeting, cargo loading, cutting stock, choosing which tests to run. It also teaches a subtle point about running times. The DP takes time, which looks polynomial, yet the problem is NP-hard. The resolution, pseudo-polynomial time, is the second half of this lesson.
The problem and the recurrence
Items have integer weights and values ; the capacity is an integer. Choose a set with maximising .
The choice for item is binary: leave it, or take it (if it fits). Let be the best value using only items with capacity . Either an optimal solution for leaves item , and then it is an optimal solution for ; or it takes item , and then the rest is an optimal solution for . Cut and paste proves both claims, so
The subproblem space needs both coordinates. Prefixes of the item list alone are not enough, because what the remaining items can do depends on how much room is left. This is the first DP in the course whose table is indexed by a number from the input rather than by positions in it, and that is exactly where the trouble with "polynomial" will come from.
The table
Four items and capacity 10:
| item | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
| weight | 4 | 3 | 2 | 5 |
| value | 10 | 7 | 4 | 12 |
Row is computed from row alone. To recover the chosen items, walk up from : if , item must have been taken, so record it and move to ; otherwise move straight up. The Python version prints the same table and the same choice as the animation.
def knapsack(weights, values, W):
n = len(weights)
K = [[0] * (W + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
w, v = weights[i - 1], values[i - 1]
for c in range(W + 1):
K[i][c] = K[i - 1][c]
if w <= c and K[i - 1][c - w] + v > K[i][c]:
K[i][c] = K[i - 1][c - w] + v
chosen, c = [], W
for i in range(n, 0, -1):
if K[i][c] != K[i - 1][c]:
chosen.append(i)
c -= weights[i - 1]
return K, sorted(chosen)
weights, values, W = [4, 3, 2, 5], [10, 7, 4, 12], 10
K, chosen = knapsack(weights, values, W)
print("c: " + " ".join(f"{c:3}" for c in range(W + 1)))
for i, row in enumerate(K):
print(f"row {i}: " + " ".join(f"{x:3}" for x in row))
print("best value", K[-1][-1], "with items", chosen,
"total weight", sum(weights[i - 1] for i in chosen))c: 0 1 2 3 4 5 6 7 8 9 10
row 0: 0 0 0 0 0 0 0 0 0 0 0
row 1: 0 0 0 0 10 10 10 10 10 10 10
row 2: 0 0 0 7 10 10 10 17 17 17 17
row 3: 0 0 4 7 10 11 14 17 17 21 21
row 4: 0 0 4 7 10 12 14 17 19 22 23
best value 23 with items [2, 3, 4] total weight 10
The best packing takes items 2, 3 and 4 for a value of 23 and fills the bag exactly. Notice that item 1 has the best value per kilogram (), yet it is not in the optimal solution; a greedy rule "best ratio first" would take items 1 and 4 (value 22) and then find that nothing else fits. The lesson Fractional and 0/1 Knapsack explains why greedy works when items can be split and fails here.
One row is enough
Since row only reads row , a single array of length suffices, if the capacities are visited from high to low. Going upward would read entries already updated for item , which amounts to taking item several times, and that solves a different problem, the unbounded knapsack.
def knapsack_1d(weights, values, W, downward=True):
K = [0] * (W + 1)
for w, v in zip(weights, values):
caps = range(W, w - 1, -1) if downward else range(w, W + 1)
for c in caps:
K[c] = max(K[c], K[c - w] + v)
return K[W]
weights, values, W = [4, 3, 2, 5], [10, 7, 4, 12], 10
print("0/1 knapsack (downward): ", knapsack_1d(weights, values, W))
print("unbounded knapsack (upward): ", knapsack_1d(weights, values, W, downward=False))0/1 knapsack (downward): 23
unbounded knapsack (upward): 24
Upward, the program may pack copies: item 1 twice plus item 3, for example, gives for weight 10, which is optimal when copies are unlimited. The direction of one loop is the entire difference between the two problems, a classic source of bugs. The same unbounded recurrence is the one behind rod cutting and coin change (Coin Change Ways counts the combinations instead of maximising).
Why is not polynomial
The table has entries with work each, so the DP takes time. Is that polynomial? Polynomial in what matters: the size of the input, the number of bits needed to write it down. The weights and values take bits if every number is at most , and the capacity takes only bits. So itself can be exponential in the input size: adding one more bit to the capacity doubles and doubles the running time, without making the input meaningfully longer.
import random
def knapsack_steps(weights, values, W):
K, steps = [0] * (W + 1), 0
for w, v in zip(weights, values):
for c in range(W, w - 1, -1):
steps += 1
K[c] = max(K[c], K[c - w] + v)
return K[W], steps
rng = random.Random(5)
n = 20
for bits in [8, 10, 12, 14, 16]:
W = 2 ** bits
weights = [rng.randint(W // 8, W // 2) for _ in range(n)]
values = [rng.randint(1, 1000) for _ in range(n)]
input_bits = sum(x.bit_length() for x in weights + values) + W.bit_length()
best, steps = knapsack_steps(weights, values, W)
print(f"W = 2^{bits:2}: input about {input_bits:4} bits, DP steps {steps:9}")W = 2^ 8: input about 319 bits, DP steps 3447
W = 2^10: input about 350 bits, DP steps 14996
W = 2^12: input about 405 bits, DP steps 56726
W = 2^14: input about 451 bits, DP steps 226916
W = 2^16: input about 488 bits, DP steps 901748
Each extra pair of bits per number adds about 40 bits to the input but multiplies the DP's work by four. In terms of the input length , the running time is exponential. An algorithm whose running time is polynomial in the numeric values of the input (here and ), but not necessarily in their bit length, is called pseudo-polynomial.
This is not a weakness of this particular DP. The decision version ("is there a packing of value at least ?") is NP-complete, and so is its special case subset sum (values equal weights: is there a subset with total exactly ?). A truly polynomial algorithm, , would prove P = NP. Problems like these, hard in general but solvable in pseudo-polynomial time, are called weakly NP-hard; problems that stay NP-hard even when all numbers are bounded by a polynomial in (such as bin packing or the travelling salesman problem) are strongly NP-hard, and have no pseudo-polynomial algorithm unless P = NP. The reductions are in Selected Topics.
In practice the distinction is benign when the numbers are small: capacities in the thousands, or weights measured in coarse units. When they are large, there is a second DP that indexes by value instead of weight, for total value , and rounding the values to fewer bits turns it into a fully polynomial-time approximation scheme, the subject of Approximation Algorithms.
In C++
The one-row 0/1 DP in C++, with a bool table on the side to reconstruct the items (one row of choices per item, still bits).
#include <cstdio>
#include <vector>
int main() {
std::vector<int> w = {4, 3, 2, 5, 7, 1, 6}, v = {10, 7, 4, 12, 15, 2, 13};
int n = static_cast<int>(w.size()), W = 15;
std::vector<int> K(W + 1, 0);
std::vector<std::vector<bool>> took(n, std::vector<bool>(W + 1, false));
for (int i = 0; i < n; ++i)
for (int c = W; c >= w[i]; --c)
if (K[c - w[i]] + v[i] > K[c]) { K[c] = K[c - w[i]] + v[i]; took[i][c] = true; }
std::printf("best value %d, items (1-based):", K[W]);
for (int i = n - 1, c = W; i >= 0; --i)
if (took[i][c]) { std::printf(" %d", i + 1); c -= w[i]; }
std::printf("\n");
}best value 35, items (1-based): 6 4 3 2 1
The reconstruction walks the items backwards: took[i][c] records whether item improved capacity when it was processed, which is exactly the condition of the two-dimensional walk. Practise with 0/1 Knapsack and Subset Sum; the DSA course has a gentler first look in The 0/1 Knapsack Problem.
Test yourself
What is when item weighs more than ?
In the one-row knapsack DP, why must the capacity loop run from down to ?
- It is faster
- Going upward would use the already-updated entries for item , allowing it to be taken more than once
- Going downward avoids negative indices
- The order does not matter
Why is the knapsack algorithm called pseudo-polynomial?
- Because it is only approximately correct
- Because can be exponential in the number of bits used to write it, so the time is not polynomial in the input size
- Because it uses floating-point numbers
- Because it is polynomial only for
Which problem is solvable in pseudo-polynomial time (assuming P NP, the others are not)?
- Subset sum
- Bin packing
- Travelling salesman
- 3-coloring of graphs