Lesson 6 · Dynamic programming

0/1 Knapsack

Pick items to carry, each at most once, so the total weight fits the bag and the total value is as large as possible. Every item is a yes-or-no choice, and a table of capacities turns 2ⁿ subsets into n × W cells.

0/1 Knapsack concept diagramThe 0/1 knapsack table for items A (weight 1, value 6), B (weight 2, value 10) and C (weight 3, value 12) with capacity 0 to 5. The answer cell, row C capacity 5, is 22. An arrow straight down from the cell above (16) shows skipping C; a curved arrow from row B capacity 2 (10) shows taking C and adding 12. Both reads come from the row above, so each item is used at most once.c = 0c = 1c = 2c = 3c = 4c = 5no items000000A · w1 v6066666B · w2 v100610161616C · w3 v120610161822skiptake C: 10 + 12dp[C][5] = max(skip 16, take 10 + 12) = 22 · items B + Cboth choices read the row above, the row without C, so no item is used twice
1

One Copy of Each Item

You have n items, each with a weight and a value, and a bag that holds at most W. Choose a set of items whose weights add up to W or less and whose values add up to as much as possible. The "0/1" means every item is either out (0) or in (1). You cannot take half an item, and you cannot take the same item twice.

This page uses three items and a bag of capacity 5: A weighs 1 and is worth 6, B weighs 2 and is worth 10, C weighs 3 and is worth 12. There are 2³ = 8 subsets. The best is B + C: weight 5, value 22. With 40 items there would be about a trillion subsets, so trying them all stops being an option very quickly.

  • Input: weights, values, capacity W (all non-negative integers here)
  • Output: the largest total value whose total weight is at most W
  • The same item set is used in the unbounded knapsack lesson, so the numbers can be compared
2

The Take-or-Skip Recurrence

  1. Make a table with rows 0 to n (items considered) and columns 0 to W (capacity)
  2. Fill row 0 with zeros: with no items, every capacity is worth 0
  3. For each item i and each capacity c, start with skip = dp[i − 1][c]
  4. If wᵢ ≤ c, compare with take = vᵢ + dp[i − 1][c − wᵢ] and keep the larger
  5. The answer is dp[n][W], the bottom-right cell

Let dp[i][c] be the best value using only the first i items with capacity c. Look at item i. Either it is not in the best answer, and the answer is dp[i − 1][c]. Or it is, and then the rest of the bag (capacity c − wᵢ) must be filled as well as possible from the first i − 1 items: vᵢ + dp[i − 1][c − wᵢ]. The best answer is the larger of the two.

This is the whole 0/1 knapsack algorithm. Both choices read row i − 1, the row that does not contain item i. That is what stops an item from being used twice: once you decide to take it, the rest of the bag is filled from the items before it.

  • Why it is correct: the best answer either contains item i or does not, and each case is a smaller knapsack on the earlier items
  • Order of items does not matter; any order gives the same dp[n][W]
3

Recovering the Chosen Items

The table gives the value, not the items. To get the items, start at dp[n][W] and walk up the rows. If dp[i][c] equals dp[i − 1][c], item i was skipped. If it is larger, item i was taken, so subtract its weight from c and continue.

On this page's set: dp[3][5] = 22 but dp[2][5] = 16, so C was taken and c drops to 2. dp[2][2] = 10 but dp[1][2] = 6, so B was taken and c drops to 0. dp[1][0] = dp[0][0] = 0, so A was skipped. The items are B and C.

  • Recovery needs the full table; the one-row version below only keeps the value
  • If several sets tie for the best value, this walk returns one of them
Key reference

Terms, operations, and practical uses

Key terms

  • CapacityThe most weight the bag can hold; one column of the table per value 0 to W.
  • dp[i][c]The best value using the first i items with capacity c.
  • Pseudo-polynomialPolynomial in the numeric value W, but exponential in the number of bits used to write W.
Implementation

Code in Python, C++ and Java

WEIGHTS = [1, 2, 3]
VALUES = [6, 10, 12]
CAPACITY = 5


def full_table(weights, values, capacity):
    n = len(weights)
    dp = [[0] * (capacity + 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(capacity + 1):
            dp[i][c] = dp[i - 1][c]
            if w <= c:
                dp[i][c] = max(dp[i][c], dp[i - 1][c - w] + v)
    return dp


def items_taken(dp, weights, capacity):
    taken, c = [], capacity
    for i in range(len(weights), 0, -1):
        if dp[i][c] != dp[i - 1][c]:
            taken.append(i - 1)
            c -= weights[i - 1]
    return taken[::-1]


def one_row(weights, values, capacity, backward):
    dp = [0] * (capacity + 1)
    for w, v in zip(weights, values):
        order = range(capacity, w - 1, -1) if backward else range(w, capacity + 1)
        for c in order:
            dp[c] = max(dp[c], dp[c - w] + v)
    return dp[capacity]


dp = full_table(WEIGHTS, VALUES, CAPACITY)
print("rows = items considered, columns = capacity 0 to", CAPACITY)
print("none   :", " ".join(map(str, dp[0])))
for i in range(len(WEIGHTS)):
    label = f"w{WEIGHTS[i]} v{VALUES[i]}"
    print(f"{label:<7}:", " ".join(map(str, dp[i + 1])))
print("best value:", dp[-1][CAPACITY])
print("items taken:", ", ".join(f"w{WEIGHTS[i]} v{VALUES[i]}" for i in items_taken(dp, WEIGHTS, CAPACITY)))
print("one row, capacity backward:", one_row(WEIGHTS, VALUES, CAPACITY, True))
print("one row, capacity forward (wrong for 0/1):", one_row(WEIGHTS, VALUES, CAPACITY, False))
print("capacity 0:", one_row(WEIGHTS, VALUES, 0, True))
#include <algorithm>
#include <cstdio>
#include <string>
#include <vector>
using namespace std;

const vector<int> WEIGHTS = {1, 2, 3};
const vector<int> VALUES = {6, 10, 12};
const int CAPACITY = 5;

vector<vector<int>> fullTable(int capacity) {
    int n = WEIGHTS.size();
    vector<vector<int>> dp(n + 1, vector<int>(capacity + 1, 0));
    for (int i = 1; i <= n; i++) {
        int w = WEIGHTS[i - 1], v = VALUES[i - 1];
        for (int c = 0; c <= capacity; c++) {
            dp[i][c] = dp[i - 1][c];
            if (w <= c) dp[i][c] = max(dp[i][c], dp[i - 1][c - w] + v);
        }
    }
    return dp;
}

int oneRow(int capacity, bool backward) {
    vector<int> dp(capacity + 1, 0);
    for (size_t i = 0; i < WEIGHTS.size(); i++) {
        int w = WEIGHTS[i], v = VALUES[i];
        if (backward)
            for (int c = capacity; c >= w; c--) dp[c] = max(dp[c], dp[c - w] + v);
        else
            for (int c = w; c <= capacity; c++) dp[c] = max(dp[c], dp[c - w] + v);
    }
    return dp[capacity];
}

string row(const vector<int>& r) {
    string s;
    for (size_t i = 0; i < r.size(); i++) s += (i ? " " : "") + to_string(r[i]);
    return s;
}

int main() {
    auto dp = fullTable(CAPACITY);
    int n = WEIGHTS.size();
    printf("rows = items considered, columns = capacity 0 to %d\n", CAPACITY);
    printf("none   : %s\n", row(dp[0]).c_str());
    for (int i = 0; i < n; i++) {
        string label = "w" + to_string(WEIGHTS[i]) + " v" + to_string(VALUES[i]);
        printf("%-7s: %s\n", label.c_str(), row(dp[i + 1]).c_str());
    }
    printf("best value: %d\n", dp[n][CAPACITY]);
    vector<int> taken;
    for (int i = n, c = CAPACITY; i > 0; i--)
        if (dp[i][c] != dp[i - 1][c]) { taken.push_back(i - 1); c -= WEIGHTS[i - 1]; }
    reverse(taken.begin(), taken.end());
    printf("items taken: ");
    for (size_t k = 0; k < taken.size(); k++)
        printf("%sw%d v%d", k ? ", " : "", WEIGHTS[taken[k]], VALUES[taken[k]]);
    printf("\n");
    printf("one row, capacity backward: %d\n", oneRow(CAPACITY, true));
    printf("one row, capacity forward (wrong for 0/1): %d\n", oneRow(CAPACITY, false));
    printf("capacity 0: %d\n", oneRow(0, true));
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    static final int[] WEIGHTS = {1, 2, 3};
    static final int[] VALUES = {6, 10, 12};
    static final int CAPACITY = 5;

    static int[][] fullTable(int capacity) {
        int n = WEIGHTS.length;
        int[][] dp = new int[n + 1][capacity + 1];
        for (int i = 1; i <= n; i++) {
            int w = WEIGHTS[i - 1], v = VALUES[i - 1];
            for (int c = 0; c <= capacity; c++) {
                dp[i][c] = dp[i - 1][c];
                if (w <= c) dp[i][c] = Math.max(dp[i][c], dp[i - 1][c - w] + v);
            }
        }
        return dp;
    }

    static int oneRow(int capacity, boolean backward) {
        int[] dp = new int[capacity + 1];
        for (int i = 0; i < WEIGHTS.length; i++) {
            int w = WEIGHTS[i], v = VALUES[i];
            if (backward)
                for (int c = capacity; c >= w; c--) dp[c] = Math.max(dp[c], dp[c - w] + v);
            else
                for (int c = w; c <= capacity; c++) dp[c] = Math.max(dp[c], dp[c - w] + v);
        }
        return dp[capacity];
    }

    static String row(int[] r) {
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < r.length; i++) s.append(i > 0 ? " " : "").append(r[i]);
        return s.toString();
    }

    public static void main(String[] args) {
        int[][] dp = fullTable(CAPACITY);
        int n = WEIGHTS.length;
        System.out.println("rows = items considered, columns = capacity 0 to " + CAPACITY);
        System.out.println("none   : " + row(dp[0]));
        for (int i = 0; i < n; i++) {
            String label = "w" + WEIGHTS[i] + " v" + VALUES[i];
            System.out.println(String.format("%-7s: ", label) + row(dp[i + 1]));
        }
        System.out.println("best value: " + dp[n][CAPACITY]);
        List<String> taken = new ArrayList<>();
        for (int i = n, c = CAPACITY; i > 0; i--)
            if (dp[i][c] != dp[i - 1][c]) { taken.add("w" + WEIGHTS[i - 1] + " v" + VALUES[i - 1]); c -= WEIGHTS[i - 1]; }
        Collections.reverse(taken);
        System.out.println("items taken: " + String.join(", ", taken));
        System.out.println("one row, capacity backward: " + oneRow(CAPACITY, true));
        System.out.println("one row, capacity forward (wrong for 0/1): " + oneRow(CAPACITY, false));
        System.out.println("capacity 0: " + oneRow(0, true));
    }
}
Watch it run

Step through it

Running on A (weight 1, value 6), B (2, 10), C (3, 12), capacity 5

itemscapacity 5A · weight 1 · value 6B · weight 2 · value 10C · weight 3 · value 12empty bagdp[c] = best value with capacity cc = 00c = 10c = 20c = 30c = 40c = 50dpEach item makes one pass over the row, from capacity 5 down to its weight.dp[c] = max(skip: dp[c], take: dp[c − w] + v)
Step 1

Start: one row of zeros

dp[c] is the best value that fits in capacity c using the items seen so far. Before any item, every capacity is worth 0. One row is enough because each item only needs the row as it was before that item.

Output
1 / 11
4

One Row: Why Capacity Goes Backward

Row i only reads row i − 1, so one array of size W + 1 can hold both: before item i is processed it is row i − 1, after it is row i. The catch is the order. dp[c] reads dp[c − w], a cell to its left. If you loop c from high to low, that cell has not been rewritten yet, so it still means "without this item", exactly as the table version needs.

Loop c upward and dp[c − w] may already include the current item, so the item gets added again. On this set, a forward sweep with item A gives 6, 12, 18, 24, 30: five copies of A. That is the right answer to a different problem, the unbounded knapsack, where every item may repeat. The tracer below shows both sweeps.

  • Backward loop: each item at most once (0/1 knapsack)
  • Forward loop: each item any number of times (unbounded knapsack)
  • The inner loop can stop at c = w; smaller capacities cannot hold the item
5

0/1 Knapsack Time Complexity

The table has (n + 1) × (W + 1) cells and each takes O(1) work, so 0/1 knapsack runs in O(n·W) time. Space is O(n·W) for the full table or O(W) for one row. For 100 items and capacity 10,000 that is a million cells, which is fast.

O(n·W) looks polynomial, but W is a number, not a count. Written in binary it takes only about log₂W bits, so adding one bit to W doubles the work. That is called pseudo-polynomial time. The decision version of knapsack is NP-complete (see P, NP and NP-complete), and the table does not contradict that: it is only fast when W is small.

  • Huge W but small values: swap the roles and store the least weight for each total value, O(n·ΣV)
  • Small n (up to about 40): split the items in half and match the two halves, about O(2^(n/2)·n)
  • Large n and W: branch and bound prunes subsets using the fractional bound
6

0/1 Knapsack vs Fractional Knapsack

In the fractional knapsack you may cut an item and take part of it. Then a greedy rule is optimal: sort by value per unit of weight and take the best ratio first, cutting the last item to fill the bag (see greedy algorithms). Between 0/1 knapsack and fractional knapsack, the difference is that whole items can leave a gap that nothing fills.

On this set the ratios are A 6, B 5, C 4. Greedy takes A and B (weight 3, value 16), and C (weight 3) no longer fits in the 2 that is left. The table finds 22. The same three items as fractions give 6 + 10 + two thirds of 12 = 24, which is always at least the 0/1 answer and is why branch and bound uses it as an upper bound.

The same three items, capacity 5
0/1 knapsackFractional knapsack
Items can be cutNoYes
MethodDynamic programming, O(n·W)Greedy by value per weight, O(n log n)
Greedy by ratio16, not optimal24, optimal
Best value22 (B + C)24 (A + B + ⅔ of C)