0/1 knapsack
🌍 In real life. Tanvir packs a bag for a trip to Cox's Bazar, and the bus allows 4 kg. He could take a camera (3 kg, worth 40 to him), a jacket (2 kg, worth 25) or food (2 kg, worth 25). Taking the most valuable thing first gives the camera, and then nothing else fits: 40. The jacket and the food together weigh 4 kg and are worth 50. Even "best value per kg first" picks the camera (13.3 per kg against 12.5). Greedy fails here, so we need a table.
The idea in one sentence: in the 0/1 knapsack each item is taken whole or left behind, and dp[i][c] is the best value from the first i items in a bag of c kg: item i is either left out (dp[i − 1][c]) or, if it fits, taken (dp[i − 1][c − w] + v), and the table keeps the better.
Its words:
- 0/1: each item is taken once (1) or not at all (0); no halves, no copies
- capacity
c: how many kg the bag may still hold; the table has a column for every capacity from 0 up - state
(i, c): the first i items, and c kg of room
Step by step:
- make a
(n + 1) × (cap + 1)table; row 0 (no items) is all 0 - for item i, weight w and value v, at every capacity c: start with
dp[i − 1][c](leave it out) - if
w <= c, try taking it:dp[i − 1][c − w] + v, and keep the larger - the answer is
dp[n][cap]; to see which items, walk back up: where the value changed, the item was taken
Watch the table find the jacket and the food:
Why it is right. Look at the best packing of the first i items in c kg. Either it doesn't use item i, and then it is the best packing of the first i − 1 items in c kg, or it does, and then the rest of it is the best packing of the first i − 1 items in the c − w kg that are left. The table holds both, so taking the larger can't miss the best.
Why c − w reads the row above. Using dp[i][c − w] (this row) would let item i be packed again; reading row i − 1 is what makes it 0/1.
What it costs, by counting. One cell per item and capacity, two lookups each: 100 items and a 1,000 kg capacity fill 100 × 1,001, about 100,000 cells. Trying every set of items instead means 2 to the power 100 sets. The table's size grows with the capacity, so with a capacity of millions it becomes slow too. In Big-O: O(n × cap) time and memory for n items and a capacity cap.
def knapsack(items, cap):
n = len(items)
dp = [[0] * (cap + 1) for _ in range(n + 1)] # dp[i][c]: the best from the first i items in c kg
for i in range(1, n + 1):
w, v = items[i - 1]
for c in range(cap + 1):
dp[i][c] = dp[i - 1][c] # leave item i out
if w <= c:
dp[i][c] = max(dp[i][c], dp[i - 1][c - w] + v) # or take it
return dp[n][cap]
def packed_items(items, cap):
n = len(items)
dp = [[0] * (cap + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
w, v = items[i - 1]
for c in range(cap + 1):
dp[i][c] = dp[i - 1][c]
if w <= c:
dp[i][c] = max(dp[i][c], dp[i - 1][c - w] + v)
taken, c = [], cap
for i in range(n, 0, -1): # walk back up the rows
if dp[i][c] != dp[i - 1][c]: # the value changed: item i was taken
taken.append(i)
c -= items[i - 1][0]
return sorted(taken)
trip = [(3, 40), (2, 25), (2, 25)]
print(knapsack(trip, 4), packed_items(trip, 4))Mistakes and edge cases.
- taking an item twice: reading
dp[i][c − w]instead ofdp[i − 1][c − w]lets one jacket be packed twice - a capacity of 0: column 0 is a real state (a full bag), and
dp[i - 1][c - w]reads it when an item fills the bag exactly, so the table needscap + 1columns, notcap - an item heavier than the bag: it is never taken; its row just copies the row above
- greedy by value or by value per kg: both fail on Tanvir's bag
- the walk back: compare
dp[i][c]withdp[i − 1][c], the same column one row up, and take off the weight only when the item was taken
Quiz
What does 0/1 mean in 0/1 knapsack?
- Each item is taken whole once, or not at all
- Each item weighs 0 or 1 kg
- The bag is empty or full
What does this print?
def knapsack(items, cap): n = len(items) dp = [[0] * (cap + 1) for _ in range(n + 1)] # dp[i][c]: the best from the first i items in c kg for i in range(1, n + 1): w, v = items[i - 1] for c in range(cap + 1): dp[i][c] = dp[i - 1][c] # leave item i out if w <= c: dp[i][c] = max(dp[i][c], dp[i - 1][c - w] + v) # or take it return dp[n][cap] print(knapsack([(1, 1), (3, 4), (4, 5), (5, 7)], 7))Item i weighs more than c. What is dp[i][c]?
- dp[i − 1][c]: it can't be taken
- 0
- dp[i − 1][c] + v
What does this print?
def packed_items(items, cap): n = len(items) dp = [[0] * (cap + 1) for _ in range(n + 1)] for i in range(1, n + 1): w, v = items[i - 1] for c in range(cap + 1): dp[i][c] = dp[i - 1][c] if w <= c: dp[i][c] = max(dp[i][c], dp[i - 1][c - w] + v) taken, c = [], cap for i in range(n, 0, -1): # walk back up the rows if dp[i][c] != dp[i - 1][c]: # the value changed: item i was taken taken.append(i) c -= items[i - 1][0] return sorted(taken) print(packed_items([(1, 6), (2, 10), (3, 12)], 5))knapsack([(2, 25)], 4) gives 50: the jacket is packed twice. Which line is wrong?
def knapsack(items, cap): n = len(items) dp = [[0] * (cap + 1) for _ in range(n + 1)] for i in range(1, n + 1): w, v = items[i - 1] for c in range(cap + 1): dp[i][c] = dp[i - 1][c] if w <= c: dp[i][c] = max(dp[i][c], dp[i][c - w] + v) return dp[n][cap]
Coding tasks
Write
knapsack(items, cap):itemsis a list of(weight, value)pairs andcapis how many kg the bag holds. Each item is taken whole or not at all. Return the best total value.Write
packed_items(items, cap): return the numbers (counting from 1) of the items in the best packing, sorted. (Every test has only one best packing.)