Knapsack
How the 0/1 knapsack table is built and read back, how the unbounded and subset-sum variants differ, and what interviewers ask about it.
On this page
The 0/1 knapsack problem gives you items that each have a weight and a value, and a capacity. You choose a set of items whose total weight is at most the capacity and whose total value is as large as possible, and each item is either taken whole or left out. It is solved with dynamic programming over a table with one row per item and one column per capacity, in O(n × W) time. You reach for it whenever you must pick whole items under a budget and a greedy rule does not work.
Greedy fails here. Take a 5 kg capacity and three items: honey (2 kg, profit 4), cheese (3 kg, profit 7) and jam (4 kg, profit 10). Jam has the best profit per kilo, so a greedy rule packs it first, and the remaining 1 kg holds nothing else, for a total of 10. Honey and cheese together weigh exactly 5 kg and earn 11. Checking every subset takes 2ⁿ steps for n items.
Why the state needs two indexes
In 1D Dynamic Programming the state was one number, such as "the best result using the first i items". That is not enough here. To decide whether item i fits, you need to know how much capacity the earlier choices left, and two packings with the same profit can leave different amounts of room. So the state has two parts, the items considered so far and the capacity available, and the table has one dimension for each, like the tables in DP on Grids.
How the table is filled
- State.
best[i][w]is the largest total value you can get from the firstiitems using at mostwkg. - Recurrence. If you skip item
i, the result isbest[i − 1][w]. If you pack it, which is possible only whenweight[i] <= w, the result isvalue[i] + best[i − 1][w − weight[i]], which is the item's value plus the best use of the remaining space by earlier items. The cell holds the larger of the two. - Base case.
best[0][w] = 0for everyw, because with no items the value is 0. - Order. Each cell reads only the row above it, so you fill the table row by row.
- Answer.
best[n][W], whereWis the full capacity.
Packing reads from the row above, never from the current row. That is what guarantees an item is used at most once: after you pack the cheese, the remaining space can only be filled with items that come earlier in the list.
The trace below fills the table for the honey, cheese and jam example.
best[0][w] = 0 for every wfor i from 1 to n: for w from 0 to W: best[i][w] = best[i-1][w] # skip item i if weight[i] <= w: take = value[i] + best[i-1][w - weight[i]] best[i][w] = max(best[i][w], take)return best[n][W]- best[i][w]
0 kg 1 kg 2 kg 3 kg 4 kg 5 kg no items 0 0 0 0 0 0 + honey (2 kg, 4) + cheese (3 kg, 7) + jam (4 kg, 10) - capacity
- 5
1The first row is the base case: with no items, every capacity earns 0. Each later row allows one more item.
- best[i][w]
0 kg 1 kg 2 kg 3 kg 4 kg 5 kg no items 0 0 0 0 0 0 + honey (2 kg, 4) 0 0 4 4 4 4 + cheese (3 kg, 7) + jam (4 kg, 10) - row
- 1
2Row 1 allows only the honey (2 kg, profit 4). It does not fit in 0 or 1 kg, so those cells stay 0. From 2 kg upward it fits, and packing it gives 4 +
best[0][w - 2]= 4, which beats skipping it (0). - best[i][w]
0 kg 1 kg 2 kg 3 kg 4 kg 5 kg no items 0 0 0 0 0 0 + honey (2 kg, 4) 0 0 4 4 4 4 + cheese (3 kg, 7) 0 0 4 7 7 11 + jam (4 kg, 10) - row
- 2
3Row 2 adds the cheese (3 kg, profit 7). It does not fit in 2 kg or less, so those cells copy the row above. At 3 kg packing gives 7 +
best[1][0]= 7, and at 4 kg it gives 7 +best[1][1]= 7. At 5 kg it gives 7 +best[1][2]= 11, which is the cheese plus the honey. - best[i][w]
0 kg 1 kg 2 kg 3 kg 4 kg 5 kg no items 0 0 0 0 0 0 + honey (2 kg, 4) 0 0 4 4 4 4 + cheese (3 kg, 7) 0 0 4 7 7 11 + jam (4 kg, 10) 0 0 4 7 10 11 - row
- 3
4Row 3 adds the jam (4 kg, profit 10). It fits only at 4 and 5 kg. At 4 kg packing gives 10 +
best[2][0]= 10, which beats the 7 above. At 5 kg packing gives 10 +best[2][1]= 10, but skipping gives 11, so the cell keeps 11. - best[i][w]
0 kg 1 kg 2 kg 3 kg 4 kg 5 kg no items 0 0 0 0 0 0 + honey (2 kg, 4) 0 0 4 4 4 4 + cheese (3 kg, 7) 0 0 4 7 7 11 + jam (4 kg, 10) 0 0 4 7 10 11 - answer
- 11
- items
- honey + cheese
5The answer is
best[3][5] = 11. To find the items, start at that cell. Its value equals the cell above it, so the jam was skipped. In row 2 the value differs from the cell above, so the cheese was packed, and the search continues atbest[1][2], where the honey was packed.
Code
function bestProfit(weights, values, capacity) {
const n = weights.length;
const best = Array.from({ length: n + 1 }, () => new Array(capacity + 1).fill(0));
for (let i = 1; i <= n; i++) {
const weight = weights[i - 1]; // row i is item i - 1 in the arrays
const value = values[i - 1];
for (let w = 0; w <= capacity; w++) {
best[i][w] = best[i - 1][w]; // skip the item
if (weight <= w) {
best[i][w] = Math.max(best[i][w], value + best[i - 1][w - weight]); // take it
}
}
}
return best[n][capacity];
}
bestProfit([2, 3, 4], [4, 7, 10], 5); // 11def best_profit(weights, values, capacity):
n = len(weights)
best = [[0] * (capacity + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
weight, value = weights[i - 1], values[i - 1] # row i is item i - 1
for w in range(capacity + 1):
best[i][w] = best[i - 1][w] # skip the item
if weight <= w:
best[i][w] = max(best[i][w], value + best[i - 1][w - weight]) # take it
return best[n][capacity]
best_profit([2, 3, 4], [4, 7, 10], 5) # 11| Approach | Time | Space | Why |
|---|---|---|---|
| Try every subset | O(2ⁿ × n) | O(n) | Each item is in or out, and adding up a subset takes up to n steps. |
| Full table | O(n × W) | O(n × W) | There are (n + 1) × (W + 1) cells, and each takes constant work. |
| One row | O(n × W) | O(W) | The same work, but you can no longer list which items were chosen. |
Variants
Listing the chosen items
The table gives the best value, but a problem often asks which items to take. Start at best[n][W] and move up one row at a time. If the cell has the same value as the cell directly above it, the item for that row was skipped. If the value differs, the item was packed, so record it and move left by its weight before going up. For the example this finds the cheese in row 2 and the honey in row 1.
function chosenItems(best, weights, capacity) {
const chosen = [];
let w = capacity;
for (let i = best.length - 1; i >= 1; i--) {
if (best[i][w] !== best[i - 1][w]) { // the value changed, so item i - 1 was packed
chosen.push(i - 1);
w -= weights[i - 1];
}
}
return chosen.reverse(); // item indexes in input order
}def chosen_items(best, weights, capacity):
chosen = []
w = capacity
for i in range(len(best) - 1, 0, -1):
if best[i][w] != best[i - 1][w]: # the value changed, so item i - 1 was packed
chosen.append(i - 1)
w -= weights[i - 1]
return chosen[::-1] # item indexes in input orderUsing one row
Each row reads only the row above, so you can keep a single array and overwrite it item by item. The packing option reads best[w − weight], a cell to the left. If you loop w upward, that cell has already been updated for the current item, so the item can be counted twice. If you loop downward, every cell to the left still holds the value from the previous item, which is what the recurrence needs. The cost is that the earlier rows are gone, so you cannot walk back through the table to list the items.
function bestProfitOneRow(weights, values, capacity) {
const best = new Array(capacity + 1).fill(0);
for (let i = 0; i < weights.length; i++) {
// High to low, so best[w - weights[i]] still comes from the previous item.
for (let w = capacity; w >= weights[i]; w--) {
best[w] = Math.max(best[w], values[i] + best[w - weights[i]]);
}
}
return best[capacity];
}def best_profit_one_row(weights, values, capacity):
best = [0] * (capacity + 1)
for weight, value in zip(weights, values):
# High to low, so best[w - weight] still comes from the previous item.
for w in range(capacity, weight - 1, -1):
best[w] = max(best[w], value + best[w - weight])
return best[capacity]Unbounded knapsack
In the unbounded version every item can be used any number of times. The recurrence barely changes, but packing now reads from the same row, best[i][w − weight[i]], because the item may be used again after it has been packed. In the one-row form this means looping w upward, which is exactly the loop that is wrong for 0/1. Coin change is the standard example. See Introduction to Dynamic Programming for coin change.
Bounded knapsack
In the bounded version each item comes with a limited number of copies, for example three of the 2 kg item. The simplest solution treats each copy as a separate 0/1 item and runs the ordinary one-row code, which costs O(W × total copies). When the counts are large, you can split a count c into pieces of sizes 1, 2, 4 and so on, with a last piece for the remainder, and treat each piece as one 0/1 item whose weight and value are multiplied by its size. Any number of copies from 0 to c can be formed from those pieces, and an item with c copies becomes only about log c items.
Subset sum and equal partition
Subset sum asks whether some subset of numbers adds up to exactly a target. It is knapsack with a yes or no answer: can[w] is true if some subset of the items seen so far sums to w, with can[0] = true, and the update is can[w] = can[w] or can[w − x] for each number x, looping w downward as in the one-row code. The "split an array into two halves with equal sums" problem is subset sum with a target of half the total, and it has no answer at all when the total is odd.
Exactly the capacity, or at most the capacity
The table above allows unused space, because best[0][w] = 0 for every w. Some problems require the weights to add up to exactly W. For those, set best[0][0] = 0 and every other cell of row 0 to negative infinity, so that a state that has not reached its capacity exactly can never be extended into a valid answer.
When knapsack does not apply
If items can be cut into fractions, such as pouring out part of a sack of rice, sorting by value per weight and taking items greedily is correct and needs no table. See Greedy Algorithms. If the capacity is huge, for example in the billions, the table has too many columns to build. With about 20 or fewer items, trying all 2ⁿ subsets is then the practical choice.
Pitfalls
In the interview
Several signals in a problem statement point to knapsack. You are given a list of items or numbers and a limit on a total such as weight, cost, time or sum. Each item is used once or not at all. You are asked for the largest value, whether a total is reachable, or how many ways reach it. The limit is small enough, usually up to a few thousand, to be a table dimension. A greedy rule seems plausible, but you can find a small counterexample. Problems such as equal-sum partition, target sum with plus and minus signs, and "pick tasks that fit in the available hours" do not mention a knapsack but have this structure.
Interviewers often ask these follow-ups.
Can you reduce the space?
Yes. Each row depends only on the previous one, so a single array of size W + 1 is enough, filled from high capacity to low so that an item is not counted twice. The time stays O(n × W). Mention the cost, which is that you can no longer reconstruct the chosen items from it.
How do you return the items and not only the value?
Keep the full table and walk back from best[n][W]. At each row, if the value equals the cell above it, the item was skipped, and otherwise it was packed and you move left by its weight.
Is this polynomial time?
It is pseudo-polynomial. The running time is O(n × W), and W is a number whose size in the input is only about log W bits, so the time is exponential in the length of the input. Knapsack is NP-hard in general, and the table does not contradict that.
What if the capacity is huge but there are few items?
Then the table is the wrong approach. With around 20 items, enumerate subsets, or split the items into two halves, list the subsets of each half, and combine them by sorting and two pointers.
What changes if items can be reused?
You switch to the unbounded form: packing reads from the same row, or in the one-row version w loops upward. Be ready to explain why the direction matters, since interviewers use it to check that you understand what the loop order means.
Items are (1 kg, profit 3) and (3 kg, profit 5), and the capacity is 3 kg. What is best[2][3]?
In the full table, why does the packing option read best[i − 1][…] and not best[i][…]?
In the one-row version for 0/1 knapsack, which direction must the capacity loop run?
What to practise next
DP on Strings uses the same two-index table, with one string along each side. To practise, try Busking Set List for 0/1 choices and Vending Machine Coin Mixes for unlimited copies.