TExcelTAD
Home › Design Techniques: Dynamic Programming, Greedy & Amortized Analysis › 0/1 Knapsack and Pseudo-Polynomial Time

0/1 Knapsack and Pseudo-Polynomial Time

A hiker can carry at most WW kilograms. Each of nn 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 Θ(nW)\Theta(nW) 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 1,…,n1, \ldots, n have integer weights wi≥1w_i \ge 1 and values vi≥0v_i \ge 0; the capacity WW is an integer. Choose a set SS with ∑i∈Swi≤W\sum_{i \in S} w_i \le W maximising ∑i∈Svi\sum_{i \in S} v_i.

The choice for item ii is binary: leave it, or take it (if it fits). Let K[i,c]K[i, c] be the best value using only items 1..i1..i with capacity cc. Either an optimal solution for (i,c)(i, c) leaves item ii, and then it is an optimal solution for (i−1,c)(i - 1, c); or it takes item ii, and then the rest is an optimal solution for (i−1,c−wi)(i - 1, c - w_i). Cut and paste proves both claims, so

K[i,c]={0if i=0,K[i−1,c]if wi>c,max⁡(K[i−1,c], K[i−1,c−wi]+vi)otherwise.K[i, c] = \begin{cases} 0 & \text{if } i = 0, \\ K[i-1, c] & \text{if } w_i > c, \\ \max\bigl(K[i-1, c],\ K[i-1, c - w_i] + v_i\bigr) & \text{otherwise.} \end{cases}

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 ii is computed from row i−1i - 1 alone. To recover the chosen items, walk up from K[n,W]K[n, W]: if K[i,c]≠K[i−1,c]K[i, c] \ne K[i-1, c], item ii must have been taken, so record it and move to c−wic - w_i; otherwise move straight up. The Python version prints the same table and the same choice as the animation.

python · try it yourself
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 (10/4=2.510/4 = 2.5), 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 ii only reads row i−1i - 1, a single array of length W+1W + 1 suffices, if the capacities are visited from high to low. Going upward would read entries already updated for item ii, which amounts to taking item ii several times, and that solves a different problem, the unbounded knapsack.

python · try it yourself
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 10+10+4=2410 + 10 + 4 = 24 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 Θ(nW)\Theta(nW) is not polynomial

The table has (n+1)(W+1)(n + 1)(W + 1) entries with O(1)O(1) work each, so the DP takes Θ(nW)\Theta(nW) time. Is that polynomial? Polynomial in what matters: the size of the input, the number of bits needed to write it down. The nn weights and values take O(nlg⁡M)O(n \lg M) bits if every number is at most MM, and the capacity takes only lg⁡W\lg W bits. So WW itself can be exponential in the input size: adding one more bit to the capacity doubles WW and doubles the running time, without making the input meaningfully longer.

python · try it yourself
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 LL, the running time is exponential. An algorithm whose running time is polynomial in the numeric values of the input (here nn and WW), 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 VV?") is NP-complete, and so is its special case subset sum (values equal weights: is there a subset with total exactly WW?). A truly polynomial algorithm, poly(n,lg⁡W)\text{poly}(n, \lg W), 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 nn (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, Θ(nV)\Theta(n V) for total value VV, 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 Θ(nW)\Theta(nW) bits).

cpp · try it yourself
#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 ii improved capacity cc when it was processed, which is exactly the condition K[i,c]≠K[i−1,c]K[i, c] \ne K[i-1, c] 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 K[i,c]K[i, c] when item ii weighs more than cc?

  1. 00
  2. K[i−1,c]K[i-1, c]
  3. K[i−1,c−wi]+viK[i-1, c - w_i] + v_i
  4. K[i,c−1]K[i, c - 1]

In the one-row knapsack DP, why must the capacity loop run from WW down to wiw_i?

  1. It is faster
  2. Going upward would use the already-updated entries for item ii, allowing it to be taken more than once
  3. Going downward avoids negative indices
  4. The order does not matter

Why is the Θ(nW)\Theta(nW) knapsack algorithm called pseudo-polynomial?

  1. Because it is only approximately correct
  2. Because WW can be exponential in the number of bits used to write it, so the time is not polynomial in the input size
  3. Because it uses floating-point numbers
  4. Because it is polynomial only for n≤Wn \le W

Which problem is solvable in pseudo-polynomial time (assuming P ≠\ne NP, the others are not)?

  1. Subset sum
  2. Bin packing
  3. Travelling salesman
  4. 3-coloring of graphs