1. Home
  2. Design & Analysis of Algorithms
  3. 0/1 Knapsack (Dynamic Programming)

0/1 Knapsack (Dynamic Programming)

Choose items to maximise value without exceeding a weight limit. Watch the DP table fill up as a 3D bar chart and trace back the chosen items.

Interactive 3DIntermediate14 min readDAAUpdated

Drag to rotate · Right-drag to pan · Click, then scroll to zoom · Space play · Left arrowRight arrow step

What's happening

A thief has a bag that holds weight W. Each item has a weight and a value, and must be taken whole or left (0/1). Which items give the most value? We fill a table where each bar’s height is the best value so far. Press Solve.

Pseudocode

  1. for i ← 0 to n: dp[i][0] ← 0; for c ← 0 to W: dp[0][c] ← 0
  2. for i ← 1 to n:
  3. for c ← 1 to W:
  4. dp[i][c] ← dp[i−1][c] // skip item i
  5. if w[i] ≤ c:
  6. dp[i][c] ← max(dp[i][c], v[i] + dp[i−1][c − w[i]]) // take it
  7. answer ← dp[n][W]; trace back to see which items were taken
Read this model as text · 31 steps

One run of the model above, written out step by step. Useful with a screen reader, on a slow connection, or for quick revision. The values may differ from the run on your screen.

  1. A thief has a bag that holds weight W. Each item has a weight and a value, and must be taken whole or left (0/1). Which items give the most value? We fill a table where each bar’s height is the best value so far. Press Solve.
  2. dp[i][c] = the best value using only the first i items with a bag of capacity c. With no items, or zero capacity, the best value is 0.
  3. Item 1 (w=1, v=1), capacity 1: skip → 0, take → 1 + dp[0][0] = 1. Best = 1 (take it!).
  4. Item 1 (w=1, v=1), capacity 2: skip → 0, take → 1 + dp[0][1] = 1. Best = 1 (take it!).
  5. Item 1 (w=1, v=1), capacity 3: skip → 0, take → 1 + dp[0][2] = 1. Best = 1 (take it!).
  6. Item 1 (w=1, v=1), capacity 4: skip → 0, take → 1 + dp[0][3] = 1. Best = 1 (take it!).
  7. Item 1 (w=1, v=1), capacity 5: skip → 0, take → 1 + dp[0][4] = 1. Best = 1 (take it!).
  8. Item 1 (w=1, v=1), capacity 6: skip → 0, take → 1 + dp[0][5] = 1. Best = 1 (take it!).
  9. Item 1 (w=1, v=1), capacity 7: skip → 0, take → 1 + dp[0][6] = 1. Best = 1 (take it!).
  10. Item 2 (w=3, v=4), capacity 1: the item weighs 3 > 1, so it can't fit. Copy the value above: 1.
  11. Item 2 (w=3, v=4), capacity 2: the item weighs 3 > 2, so it can't fit. Copy the value above: 1.
  12. Item 2 (w=3, v=4), capacity 3: skip → 1, take → 4 + dp[1][0] = 4. Best = 4 (take it!).
  13. Item 2 (w=3, v=4), capacity 4: skip → 1, take → 4 + dp[1][1] = 5. Best = 5 (take it!).
  14. Item 2 (w=3, v=4), capacity 5: skip → 1, take → 4 + dp[1][2] = 5. Best = 5 (take it!).
  15. Item 2 (w=3, v=4), capacity 6: skip → 1, take → 4 + dp[1][3] = 5. Best = 5 (take it!).
  16. Item 2 (w=3, v=4), capacity 7: skip → 1, take → 4 + dp[1][4] = 5. Best = 5 (take it!).
  17. Item 3 (w=4, v=5), capacity 1: the item weighs 4 > 1, so it can't fit. Copy the value above: 1.
  18. Item 3 (w=4, v=5), capacity 2: the item weighs 4 > 2, so it can't fit. Copy the value above: 1.
  19. Item 3 (w=4, v=5), capacity 3: the item weighs 4 > 3, so it can't fit. Copy the value above: 4.
  20. Item 3 (w=4, v=5), capacity 4: skip → 5, take → 5 + dp[2][0] = 5. Best = 5.
  21. Item 3 (w=4, v=5), capacity 5: skip → 5, take → 5 + dp[2][1] = 6. Best = 6 (take it!).
  22. Item 3 (w=4, v=5), capacity 6: skip → 5, take → 5 + dp[2][2] = 6. Best = 6 (take it!).
  23. Item 3 (w=4, v=5), capacity 7: skip → 5, take → 5 + dp[2][3] = 9. Best = 9 (take it!).
  24. Item 4 (w=5, v=7), capacity 1: the item weighs 5 > 1, so it can't fit. Copy the value above: 1.
  25. Item 4 (w=5, v=7), capacity 2: the item weighs 5 > 2, so it can't fit. Copy the value above: 1.
  26. Item 4 (w=5, v=7), capacity 3: the item weighs 5 > 3, so it can't fit. Copy the value above: 4.
  27. Item 4 (w=5, v=7), capacity 4: the item weighs 5 > 4, so it can't fit. Copy the value above: 5.
  28. Item 4 (w=5, v=7), capacity 5: skip → 6, take → 7 + dp[3][0] = 7. Best = 7 (take it!).
  29. Item 4 (w=5, v=7), capacity 6: skip → 6, take → 7 + dp[3][1] = 8. Best = 8 (take it!).
  30. Item 4 (w=5, v=7), capacity 7: skip → 9, take → 7 + dp[3][2] = 8. Best = 9.
  31. Answer: dp[4][7] = 9. Tracing back (wherever the value changed from the row above, that item was taken): items #2, #3 with total weight 7. Time and space: O(n × W).

Try this in the 3D model

  • Pause on any cell and check the two highlighted cells it is computed from.
  • Notice that the tallest bar is always in the bottom-right corner — that's the answer.
  • Change the Capacity W and solve again. Which items get picked now?
  • Try Random items and guess the best choice before pressing Solve.

The problem

A thief has a bag that can carry at most W kg. There are n items, each with a weight w[i] and a value v[i]. Each item can be taken whole or not at all — that’s the “0/1”. Which items maximise the total value without breaking the bag?

Trying every subset means 2ⁿ possibilities — about a million for 20 items and a trillion for 40. Dynamic programming solves it in O(n × W).

Dynamic programming in one sentence

Solve small versions of the problem first, store their answers in a table, and build bigger answers from smaller ones.

Here, the small version is: “What is the best value using only the first i items, with a bag of capacity c?” We call that dp[i][c].

The recurrence: skip or take

For item i and capacity c there are only two choices:

  • Skip it → the value is dp[i−1][c] (best without this item).
  • Take it (only if w[i] ≤ c) → v[i] + dp[i−1][c − w[i]] (its value plus the best we can do with the remaining capacity).
dp[i][c] = dp[i−1][c]                                   if w[i] > c
dp[i][c] = max(dp[i−1][c], v[i] + dp[i−1][c − w[i]])    otherwise

Base case: dp[0][c] = 0 (no items) and dp[i][0] = 0 (no capacity).

In the 3D model each cell is a bar whose height is its value. When a cell is computed, the cell directly above (skip, yellow) and the cell above-left by w[i] (take, purple) light up.

Tracing back the chosen items

The answer is dp[n][W]. To find which items were taken, start at the bottom-right cell and walk up: if dp[i][c] ≠ dp[i−1][c], item i was taken, so subtract its weight from c. The model highlights this path in green.

Code

def knapsack(weights, values, W):
    n = len(weights)
    dp = [[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):
            dp[i][c] = dp[i - 1][c]                        # skip
            if w <= c:
                dp[i][c] = max(dp[i][c], v + dp[i - 1][c - w])   # take
    # trace back
    chosen, c = [], W
    for i in range(n, 0, -1):
        if dp[i][c] != dp[i - 1][c]:
            chosen.append(i)
            c -= weights[i - 1]
    return dp[n][W], chosen[::-1]

print(knapsack([1, 3, 4, 5], [1, 4, 5, 7], 7))   # (9, [2, 3])
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> w = {1, 3, 4, 5}, v = {1, 4, 5, 7};
    int n = w.size(), W = 7;
    // Space-saving version: one row, filled from right to left.
    vector<int> dp(W + 1, 0);
    for (int i = 0; i < n; i++)
        for (int c = W; c >= w[i]; c--)
            dp[c] = max(dp[c], v[i] + dp[c - w[i]]);
    cout << dp[W] << "\n";   // 9
}

The C++ version uses a single row of size W + 1. Going right to left makes sure each item is used at most once — a classic interview follow-up.

0/1 vs fractional knapsack

0/1 knapsack Fractional knapsack
Items Whole or nothing Can take a fraction
Best method Dynamic programming, O(nW) Greedy by value/weight ratio, O(n log n)

The DP recipe (works for many problems)

  1. Define the state: what does dp[i][c] mean?
  2. Find the recurrence: how does a state depend on smaller states?
  3. Set base cases.
  4. Fill the table in the right order.
  5. Read the answer (and trace back if you need the choices).

The same recipe solves Longest Common Subsequence, coin change, edit distance and many more.

Common mistakes

  • Iterating capacity left-to-right in the 1-row version (lets an item be used twice — that’s the unbounded knapsack).
  • Off-by-one errors between item numbers (1-based in the table) and list indexes (0-based).
  • Forgetting the “doesn’t fit” case.

Complexity at a glance

Case / operationTimeWhy
Fill the tableO(n × W)One constant-time decision per cell.
Trace back the itemsO(n)
Brute force (try every subset)O(2ⁿ)Hopeless beyond ~30 items.
Extra spaceO(n × W)

Quick check

Test yourself — pick an answer to see if you got it.

1. What does dp[i][c] mean?

2. If item i has weight 4 and the capacity c is 3, what is dp[i][c]?

3. Why is a greedy choice (highest value per kg first) not always correct for 0/1 knapsack?

4. The DP algorithm runs in O(n × W). Why is it called "pseudo-polynomial"?

Saved in this browser.
Spotted a mistake or a bug in the 3D model?

Report a mistake

in 0/1 Knapsack (Dynamic Programming). Thank you — every report makes the lesson better for the next reader.

We'll also include a link to the step of the 3D model you're on and your browser type, so we can reproduce it.