GeeksforGeeks Medium

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.

Constraints
  • 1 <= W <= 10^3
  • 1 <= val[i], wt[i] <= 10^3
  • 1 <= val.size() = wt.size() <= 10^3
dpknapsack
Open on GeeksforGeeks ↗
02

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 capacity c - 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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def knapsack(self, W, val, wt):
▶3 dp = [0] * (W + 1)
▶4 for v, w in zip(val, wt):
▶5 for c in range(W, w - 1, -1):
▶6 dp[c] = max(dp[c], v + dp[c - w])
▶7 return dp[W]
itemsvalue 10weight 5value 40weight 4value 30weight 2value 50weight 3best value within capacity0cap 00cap 10cap 20cap 30cap 40cap 5no comparison yetno items yet → every capacity is worth 0
W5capacity
dp[0, 0, 0, 0, 0, 0]
Each box holds the best value that fits within that capacity using the items handled so far. With no items yet, every capacity is worth 0. Starting from 0 everywhere also means a capacity may be left partly empty.
itemsvalue 10weight 5value 40weight 4value 30weight 2value 50weight 3best value within capacity0cap 00cap 10cap 20cap 30cap 40cap 5no comparison yetnext item: sweep capacity 5 down to 5
value10
weight5
The sweep runs from capacity 5 down to 5, right to left. Cells below 5 cannot hold this item, so they keep their values.
itemsvalue 10weight 5value 40weight 4value 30weight 2value 50weight 3best value within capacity0cap 00cap 10cap 20cap 30cap 410cap 5take10+0=10keep0capacity 5: take 10 beats keep 0 → 10
c5capacity
take10 + 0 = 10
dp[5]10
Packing this item uses 5 of the 5 units and leaves 0, worth 0 without this item. Take gives 10 + 0 = 10, more than the 0 already there, so the box becomes 10.
itemsvalue 10weight 5value 40weight 4value 30weight 2value 50weight 3best value within capacity0cap 00cap 10cap 20cap 30cap 410cap 5no comparison yetnext item: sweep capacity 5 down to 4
value40
weight4
The sweep runs from capacity 5 down to 4, right to left. Cells below 4 cannot hold this item, so they keep their values.
itemsvalue 10weight 5value 40weight 4value 30weight 2value 50weight 3best value within capacity0cap 00cap 10cap 20cap 30cap 440cap 5take40+0=40keep10capacity 5: take 40 beats keep 10 → 40
c5capacity
take40 + 0 = 40
dp[5]40
Packing this item uses 4 of the 5 units and leaves 1, worth 0 without this item (that box is to the left, so it has not been updated yet). Take gives 40 + 0 = 40, more than the 10 already there, so the box becomes 40.
itemsvalue 10weight 5value 40weight 4value 30weight 2value 50weight 3best value within capacity0cap 00cap 10cap 20cap 340cap 440cap 5take40+0=40keep0capacity 4: take 40 beats keep 0 → 40
c4capacity
take40 + 0 = 40
dp[4]40
Packing this item uses 4 of the 4 units and leaves 0, worth 0 without this item. Take gives 40 + 0 = 40, more than the 0 already there, so the box becomes 40.
itemsvalue 10weight 5value 40weight 4value 30weight 2value 50weight 3best value within capacity0cap 00cap 10cap 20cap 340cap 440cap 5no comparison yetnext item: sweep capacity 5 down to 2
value30
weight2
The sweep runs from capacity 5 down to 2, right to left. Cells below 2 cannot hold this item, so they keep their values.
itemsvalue 10weight 5value 40weight 4value 30weight 2value 50weight 3best value within capacity0cap 00cap 10cap 20cap 340cap 440cap 5take30+0=30keep40capacity 5: take 30 loses to keep 40
c5capacity
take30 + 0 = 30
dp[5]40
Packing this item uses 2 of the 5 units and leaves 3, worth 0 without this item (that box is to the left, so it has not been updated yet). Take gives 30, which does not beat the 40 already there, so the box stays 40.
itemsvalue 10weight 5value 40weight 4value 30weight 2value 50weight 3best value within capacity0cap 00cap 10cap 20cap 340cap 440cap 5take30+0=30keep40capacity 4: take 30 loses to keep 40
c4capacity
take30 + 0 = 30
dp[4]40
Packing this item uses 2 of the 4 units and leaves 2, worth 0 without this item (that box is to the left, so it has not been updated yet). Take gives 30, which does not beat the 40 already there, so the box stays 40.
itemsvalue 10weight 5value 40weight 4value 30weight 2value 50weight 3best value within capacity0cap 00cap 10cap 230cap 340cap 440cap 5take30+0=30keep0capacity 3: take 30 beats keep 0 → 30
c3capacity
take30 + 0 = 30
dp[3]30
Packing this item uses 2 of the 3 units and leaves 1, worth 0 without this item (that box is to the left, so it has not been updated yet). Take gives 30 + 0 = 30, more than the 0 already there, so the box becomes 30.
itemsvalue 10weight 5value 40weight 4value 30weight 2value 50weight 3best value within capacity0cap 00cap 130cap 230cap 340cap 440cap 5take30+0=30keep0capacity 2: take 30 beats keep 0 → 30
c2capacity
take30 + 0 = 30
dp[2]30
Packing this item uses 2 of the 2 units and leaves 0, worth 0 without this item. Take gives 30 + 0 = 30, more than the 0 already there, so the box becomes 30.
itemsvalue 10weight 5value 40weight 4value 30weight 2value 50weight 3best value within capacity0cap 00cap 130cap 230cap 340cap 440cap 5no comparison yetnext item: sweep capacity 5 down to 3
value50
weight3
The sweep runs from capacity 5 down to 3, right to left. Cells below 3 cannot hold this item, so they keep their values.
itemsvalue 10weight 5value 40weight 4value 30weight 2value 50weight 3best value within capacity0cap 00cap 130cap 230cap 340cap 480cap 5take50+30=80keep40capacity 5: take 80 beats keep 40 → 80
c5capacity
take50 + 30 = 80
dp[5]80
Packing this item uses 3 of the 5 units and leaves 2, worth 30 without this item (that box is to the left, so it has not been updated yet). Take gives 50 + 30 = 80, more than the 40 already there, so the box becomes 80.
itemsvalue 10weight 5value 40weight 4value 30weight 2value 50weight 3best value within capacity0cap 00cap 130cap 230cap 350cap 480cap 5take50+0=50keep40capacity 4: take 50 beats keep 40 → 50
c4capacity
take50 + 0 = 50
dp[4]50
Packing this item uses 3 of the 4 units and leaves 1, worth 0 without this item (that box is to the left, so it has not been updated yet). Take gives 50 + 0 = 50, more than the 40 already there, so the box becomes 50.
itemsvalue 10weight 5value 40weight 4value 30weight 2value 50weight 3best value within capacity0cap 00cap 130cap 250cap 350cap 480cap 5take50+0=50keep30capacity 3: take 50 beats keep 30 → 50
c3capacity
take50 + 0 = 50
dp[3]50
Packing this item uses 3 of the 3 units and leaves 0, worth 0 without this item. Take gives 50 + 0 = 50, more than the 30 already there, so the box becomes 50.
itemsvalue 10weight 5value 40weight 4value 30weight 2value 50weight 3best value within capacity0cap 00cap 130cap 250cap 350cap 480cap 5answer: 80
dp[5]80best within capacity 5
Every item has been considered once. The last box covers the full capacity 5, so the best total value is 80.
05

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.

▶1class Solution:
▶2 def knapsack(self, W, val, wt):
▶3 n = len(val)
▶4 dp = [[0] * (W + 1) for _ in range(n + 1)]
▶5 for i in range(1, n + 1):
▶6 v, w = val[i - 1], wt[i - 1]
▶7 for c in range(W + 1):
▶8 dp[i][c] = dp[i - 1][c]
▶9 if w <= c:
▶10 dp[i][c] = max(dp[i][c], v + dp[i - 1][c - w])
▶11 return dp[n][W]
06

Common pitfalls

Packing greedily by value per weight

✗ Wrong
items.sort(key=lambda it: it[0] / it[1], reverse=True)
for v, w in items:
    if w <= W:
        total += v
        W -= w
✓ Right
for 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

✗ Wrong
for c in range(w, W + 1):
    dp[c] = max(dp[c], v + dp[c - w])
✓ Right
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

✗ Wrong
def knapsack(self, W, wt, val):
✓ Right
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).

07

Edge cases

Every item is heavier than W

For each item the loop from W down to its weight is empty, so the row stays at 0 and the answer is 0.

An item weighs exactly W

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.

08

Complexity

Time
O(n · W)
Space
O(W)
Each of the n items updates at most W + 1 cells, each in O(1). Only one row of W + 1 values is stored; the full table version needs (n + 1) · (W + 1).
09

Three knapsack variants, three methods

The rules about how much of an item you may take decide the method.

VariantHow much of an itemMethodCapacity loop
0/1 knapsackwhole item, at most onceDP over capacitydownwards
Unbounded knapsackwhole items, any number of copiesDP over capacityupwards
Fractional knapsackany fraction of an itemgreedy by value per weightno table
10

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.