0/1 Knapsack
0/1 Knapsack is a GFG problem (Medium). You get a capacity W and n items, where item i has value val[i] and weight wt[i]. Choose items whose total weight is at most W and whose total value is as large as possible.
- Each item is either packed whole or left out, and it can be packed only once. Those two choices are the 0 and the 1 in the name.
- Return only the best total value.
Both n and W are at most 1,000, so a table with one entry per item and capacity, about a million entries, is fast. Trying all 2^n subsets of items is not.
- 1 <= W <= 10^3
- 1 <= val[i], wt[i] <= 10^3
- 1 <= val.size() = wt.size() <= 10^3
Intuition
A best packing either leaves an item out, and is then a best packing of the other items in the same capacity, or packs it, and is then its value plus a best packing of the others in the capacity that is left:
- Skip: best value of the earlier items with capacity
c. - Take:
val +best value of the earlier items with capacityc - wt, if the item fits.
There are only n · W different (items, capacity) pairs, so solving each pair once replaces the 2^n subsets. Both choices read answers that do not include the current item yet, and that is what limits each item to one use.
Pick a subset of things, each used at most once, under one numeric budget, to maximise or reach a total: Partition Equal Subset Sum, Target Sum, Last Stone Weight II and Ones and Zeroes all reduce to this take-or-skip table.
Approach
Before reading on, decide what two numbers describe a smaller version of the problem, and write the best value of that smaller version in terms of the choice for one item. Aim for O(n · W) time, then O(W) space.
Two ways to fill the table
Update a single row of W + 1 values once per item, from the right.
- Small: about 1,000 numbers instead of a million.
- Short: three lines inside the method.
The usual interview answer.
Row i holds the best values using the first i items.
- Easier to picture: every state stays visible.
- Recovers the items: walking back up the rows shows which items were packed.
Pick it when the chosen items are needed.
Both fill the same n · W states. The single row wins on memory and is the version traced below; the full table follows the demo.
Start from take or skip
A recursion best(i, c) tries both choices for item i and returns the larger. It meets the same (i, c) pairs again and again, so caching each pair (memoization) brings it down to O(n · W). The table below computes the same pairs bottom-up, without recursion.
Keep one row of best values
Let dp[c] be the best value within capacity c using the items processed so far. Start with every entry at 0, since no items means no value. Each item then updates the row once, and the row never needs the items before it again.
Sweep capacity from W down to the item's weight
For an item of weight w and value v, set dp[c] = max(dp[c], v + dp[c - w]) for c from W down to w. Going downwards, dp[c - w] still holds the value from before this item, because cells to the left are updated later. Capacities below w cannot hold the item and keep their values.
Why dp[W] is the answer
Because the row starts at 0 everywhere, dp[c] means the best value with total weight at most c, not exactly c: unused space costs nothing. After the last item, dp[W] is therefore the best value for the full capacity.
Code in Python, C++ and Java
Full table, one row per item
Row i uses the first i items. Each cell copies the cell above (skip) and, when the item fits, compares it with the item's value plus the cell above and wt columns to the left (take). Because both choices read the previous row, the capacity loop can run in either direction here.
Common pitfalls
Packing greedily by value per weight
items.sort(key=lambda it: it[0] / it[1], reverse=True)
for v, w in items:
if w <= W:
total += v
W -= wfor c in range(W, w - 1, -1):
dp[c] = max(dp[c], v + dp[c - w])Greedy is only safe when items can be cut. With W = 50, val = [60, 100, 120] and wt = [10, 20, 30], it packs the first two items for 160 and the third no longer fits; packing the second and third gives 220.
Sweeping capacity upwards with one row
for c in range(w, W + 1):
dp[c] = max(dp[c], v + dp[c - w])for c in range(W, w - 1, -1):
dp[c] = max(dp[c], v + dp[c - w])Going up, dp[c - w] may already include this item, so it is packed again. With W = 4, val = [3] and wt = [2], the upward loop returns 6 by packing the single item twice; the answer is 3.
Mixing up the argument order
def knapsack(self, W, wt, val):
def knapsack(self, W, val, wt):
The judge passes values before weights. With the names swapped, W = 4, val = [1, 2, 3], wt = [4, 5, 1] is read as weights 1, 2, 3 and returns 9, while the real answer is 3 (only the last item fits).
Edge cases
For each item the loop from W down to its weight is empty, so the row stays at 0 and the answer is 0.
Only c = W can hold it, and it reads dp[0], which is always 0, so packing it alone is compared with the best of the other items.
Complexity
Three knapsack variants, three methods
The rules about how much of an item you may take decide the method.
| Variant | How much of an item | Method | Capacity loop |
|---|---|---|---|
| 0/1 knapsack | whole item, at most once | DP over capacity | downwards |
| Unbounded knapsack | whole items, any number of copies | DP over capacity | upwards |
| Fractional knapsack | any fraction of an item | greedy by value per weight | no table |
0/1 Knapsack FAQ
If a table solves it, why is the knapsack problem NP-hard?
Solving the knapsack using dynamic programming takes n · W steps, and W is a number, not a count of inputs. Written in b bits, W can be as large as 2^b, so the running time is exponential in the input's length. That is called pseudo-polynomial. With W up to 1,000 the table is tiny; with W around 10^12 it is impossible, and methods such as branch and bound or meet in the middle take over.
How do you find which items were packed?
Keep the full table. Start at row n, column W. If the cell differs from the cell above it, item n was packed: note it and move left by its weight. Either way, move up one row and repeat until row 0. The single row overwrites the history this walk needs.