0/1 knapsack
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)The 0/1 knapsack problem is the foundation of combinatorial dynamic programming. We explore the brute-force recursion tree first to see why storing subproblem capacities is essential.
Brute Force Recursion and Exponential Branching
The 0/1 knapsack problem chooses items, each taken whole or not at all, to get the most value without going over a weight limit.
Given n items with weights and values and a backpack of capacity W, we want the most value without going over W. Each item is taken whole or skipped.
Step by step
Step 1 of 7
| Row | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| none | 0 | 0 | 0 | 0 | 0 | 0 |
| item1 | 0 | 0 | 0 | 0 | 0 | 0 |
| item2 | 0 | 0 | 0 | 0 | 0 | 0 |
| item3 | 0 | 0 | 0 | 0 | 0 | 0 |
- item
- none
- cap
- 0
Example 1 · 0/1 Knapsack, Plain Recursion: O(2^n) Time
public class KnapRecursion { static int calls = 0;
public static int best(int[] wt, int[] val, int i, int cap) { calls++; if (i == wt.length) return 0; int skip = best(wt, val, i + 1, cap); if (wt[i] > cap) return skip; int take = val[i] + best(wt, val, i + 1, cap - wt[i]); return Math.max(skip, take); }
public static void main(String[] args) { int[] wt = {1, 2, 2, 3, 3, 4, 4, 5}; int[] val = {2, 3, 4, 4, 5, 6, 6, 8}; System.out.println("Max value for cap 10: " + best(wt, val, 0, 10)); System.out.println("Calls made: " + calls); }}Max value for cap 10: 17 Calls made: 288
What this code does
- Each item doubles the number of branches, so n items can give up to 2^n calls.
- Many branches reach the same pair (item i, remaining capacity), for example taking one of two weight-2 items and skipping the other leaves the same capacity either way.
- This small input already needs 288 calls.
Example 2 · 0/1 Knapsack, Memoization: O(n x W) Time, O(n x W) Space
import java.util.Arrays;
public class KnapMemo { static int calls = 0;
public static int best(int[] wt, int[] val, int i, int cap, int[][] memo) { calls++; if (i == wt.length) return 0; if (memo[i][cap] != -1) return memo[i][cap]; int result = best(wt, val, i + 1, cap, memo); if (wt[i] <= cap) { result = Math.max(result, val[i] + best(wt, val, i + 1, cap - wt[i], memo)); } memo[i][cap] = result; return result; }
public static void main(String[] args) { int[] wt = {1, 2, 2, 3, 3, 4, 4, 5}; int[] val = {2, 3, 4, 4, 5, 6, 6, 8}; int[][] memo = new int[wt.length][11]; for (int[] row : memo) Arrays.fill(row, -1); System.out.println("Max value for cap 10: " + best(wt, val, 0, 10, memo)); System.out.println("Calls made: " + calls); }}Max value for cap 10: 17 Calls made: 97
What this code does
- memo[i][cap] stores the best value from items i onward with capacity cap; -1 means not computed yet.
- There are at most 8 x 11 pairs, and many are never reached: calls fall from 288 to 97.
- The cost is an n by (W + 1) memo table plus recursion depth n.
With plain recursion, at item i we make a binary choice: skip item i (move to item i + 1 with capacity w), or take item i (add val[i] and move to item i + 1 with remaining capacity w - wt[i]).
Why is this slow? With n items, this binary decision tree branches 2^n times. For n = 30 items, 2^30 is over 1 billion operations. Yet many subsets of items sum to the exact same total weight, meaning the function solves the exact same remaining capacity over and over.
The 2D Dynamic Programming Table
Define dp[i][w] as the maximum value obtainable using a subset of the first i items with remaining capacity w.
Example 3 · 0/1 Knapsack, 2D Table: O(n x W) Time, O(n x W) Space
public class Knapsack2DDemo { public static int knapsack(int[] wt, int[] val, int W) { int n = wt.length; int[][] dp = new int[n + 1][W + 1]; for (int i = 1; i <= n; i++) { for (int w = 1; w <= W; w++) { if (wt[i - 1] <= w) { dp[i][w] = Math.max(dp[i - 1][w], dp[i - 1][w - wt[i - 1]] + val[i - 1]); } else { dp[i][w] = dp[i - 1][w]; } } } return dp[n][W]; }
public static void main(String[] args) { int[] wt = {2, 3, 4}; int[] val = {3, 4, 5}; System.out.println("Max value for cap 5: " + knapsack(wt, val, 5)); }}Max value for cap 5: 7
What this code does
- Creates table of dimensions (n + 1) by (W + 1) initialized to 0.
- Compares skipping the item against taking the item.
- Items with weights 2 and 3 yield maximum value 3 + 4 = 7.
If item i is too heavy (wt[i - 1] > w), we must skip it: dp[i][w] = dp[i - 1][w]. If it fits, we pick the better of skipping or taking it: dp[i][w] = Math.max(dp[i - 1][w], val[i - 1] + dp[i - 1][w - wt[i - 1]]). Base cases set dp[0][w] = 0 (no items) and dp[i][0] = 0 (zero capacity). Filling the table takes O(n * W) time and O(n * W) space.
Compressing to One Row with a Reverse Loop
Notice that row i only depends on values from row i - 1. We can compress the entire 2D table into a single 1D array dp[w] of size W + 1.
Example 4 · 0/1 Knapsack, One Row: O(n x W) Time, O(W) Space
public class Knapsack1DReverseDemo { public static int knapsack1D(int[] wt, int[] val, int W) { int[] dp = new int[W + 1]; for (int i = 0; i < wt.length; i++) { int w_i = wt[i]; int v_i = val[i]; for (int c = W; c >= w_i; c--) { dp[c] = Math.max(dp[c], dp[c - w_i] + v_i); } } return dp[W]; }
public static void main(String[] args) { int[] wt = {2, 3, 4}; int[] val = {3, 4, 5}; System.out.println("1D knapsack max value: " + knapsack1D(wt, val, 5)); }}1D knapsack max value: 7
What this code does
- Iterates capacity backward from W down to item weight.
- Prevents using item i multiple times within the same iteration.
- Achieves identical result 7 while reducing auxiliary space to O(W).
Here is the critical rule: the capacity loop must iterate in reverse, from W down to wt[i - 1]. Why reverse? If we looped forward, dp[w - wt] would already be updated with item i on the current pass. Reading it would accidentally include item i twice or more. Walking backward ensures dp[w - wt] still holds the value from the previous item.
Find the bug
Find the wrong line
Each 0/1 knapsack method has one wrong line. Tap it, then check.
One row, each item usable once. Which line breaks the answer?
Round 1 of 3Item Reconstruction and Budgeting Applications
Finding the maximum value is often not enough; we need to know exactly which items were chosen.
Example 5 · Reconstructing Selected Knapsack Items
import java.util.ArrayList;import java.util.List;
public class KnapsackReconstructDemo { public static List<Integer> getItems(int[] wt, int[] val, int W) { int n = wt.length; int[][] dp = new int[n + 1][W + 1]; for (int i = 1; i <= n; i++) { for (int w = 1; w <= W; w++) { if (wt[i - 1] <= w) { dp[i][w] = Math.max(dp[i - 1][w], dp[i - 1][w - wt[i - 1]] + val[i - 1]); } else { dp[i][w] = dp[i - 1][w]; } } } List<Integer> chosen = new ArrayList<>(); int w = W; for (int i = n; i > 0; i--) { if (dp[i][w] != dp[i - 1][w]) { chosen.add(i - 1); w -= wt[i - 1]; } } return chosen; }
public static void main(String[] args) { int[] wt = {2, 3, 4}; int[] val = {3, 4, 5}; List<Integer> items = getItems(wt, val, 5); System.out.println("Chosen item indices: " + items); }}Chosen item indices: [1, 0]
What this code does
- Compares dp[i][w] with dp[i - 1][w] to test whether item i was included.
- Deducts item weight from capacity whenever an inclusion is detected.
- Items 1 (weight 3) and 0 (weight 2) form the optimal combination.
Starting from dp[n][W], if dp[i][w] == dp[i - 1][w], item i was skipped. If dp[i][w] differs, item i was taken: record item i and subtract its weight from w: w = w - wt[i - 1]. This decision process models financial budgeting, knapsack packing, and server resource allocation.
Next step
Check your understanding
10 quick questions