0/1 knapsack
Level 2 of 3
Also called Zero-one knapsack problem and Knapsack, by dynamic programming.
how it works
The idea on the watch page's first example, three items and a bag that holds 5. The books this site follows pack a removal van the same way (volume three, chapter 39). Then the whole method on that example, step by step.
A bag holds a weight of 5. Item A weighs 4 and is worth 50, B weighs 2 and is worth 30, and C weighs 3 and is worth 40. Each item goes in whole or not at all. Taking the most valuable first takes A, and then nothing else fits: 50. But B and C together weigh 5 and are worth 70. Taking the most valuable first misses this, and taking the most value per weight first fails on other bags, as the books warn (volume three, chapter 39). So fill a table. Each row adds one item to those above it: none, then A, then B, then C. Each column is a room, from 0 to 5. A cell holds the most value its row's items can carry in its column's room. With no items or no room, that is 0. Fill the other cells row by row. Look at the row's own item. If it weighs more than the room, it cannot go in, so copy the cell above. If not, take the more of two numbers. Leaving it keeps the cell above. Taking it is its value, plus the row above at the room it leaves. For C in room 5: leaving C keeps 50. C weighs 3, so taking it leaves room 5 less 3, which is 2, and the row above holds 30 there. Taking it is 40 plus 30: 70. The cell holds 70. The last cell is the answer: 70. To see which items, read back from it. A cell worth more than the one above took its item: step up a row, to the room the item leaves. A cell worth the same did not: step straight up. This page counts cells, one for each cell the rule fills, not the first row and column: 15 here, as the watch page counts. The code below, in the language Python, fills the table and returns the last cell; it leaves reading back out.
| item | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| - | 0 | 0 | 0 | 0 | 0 |
| A | 0 | 0 | 0 | 50 | 50 |
| B | 0 | 30 | 30 | 50 | 50 |
| C | 0 | 30 | 40 | 50 | 70 |
| cell | holds | above | item |
|---|---|---|---|
| C at room 5 | 70 | 50 | in, leaves room 2 |
| B at room 2 | 30 | 0 | in, leaves room 0 |
| A at room 0 | 0 | 0 | out |
step 1 of 17
Pack a bag that holds 5 with the most value from 3 items. With no items or no room it holds nothing, so the first row and column are 0.
what it remembers to know where it is
- item
- not yet
- room
- not yet
Where it says not yet, nothing is held there at that moment.
step 2 of 17
Item A weighs 4, more than the room of 1, so it cannot go in. Keep 0 from the cell above.
what it remembers to know where it is
- item
- A
- room
- 1
step 5 of 17
With room 4, leaving A out keeps 0. Taking it is worth 50, plus 0 for the room it leaves: 50. Taking it is better, so write 50.
what it remembers to know where it is
- item
- A
- room
- 4
step 8 of 17
With room 2, leaving B out keeps 0. Taking it is worth 30, plus 0 for the room it leaves: 30. Taking it is better, so write 30.
what it remembers to know where it is
- item
- B
- room
- 2
step 10 of 17
With room 4, leaving B out keeps 50. Taking it is worth 30, plus 0 for the room it leaves: 30. That is no better, so leave it and write 50.
what it remembers to know where it is
- item
- B
- room
- 4
step 14 of 17
With room 3, leaving C out keeps 30. Taking it is worth 40, plus 0 for the room it leaves: 40. Taking it is better, so write 40.
what it remembers to know where it is
- item
- C
- room
- 3
step 16 of 17
With room 5, leaving C out keeps 50. Taking it is worth 40, plus 30 for the room it leaves: 70. Taking it is better, so write 70.
what it remembers to know where it is
- item
- C
- room
- 5
step 17 of 17
Done: take B and C, weighing 5 in all and worth 70, the most the bag holds. The marked cells are where each item went in.
what it remembers to know where it is
- item
- not yet
- room
- not yet
Where it says not yet, nothing is held there at that moment.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- the first row and column: with no items or no room, the bag holds nothingPython lines 8 and 9
- for each item, and each room from 1 up to what the bag holdsPython lines 10, 11 and 12
- too heavy for the room, so keep the best without it, the cell abovePython lines 13 and 14
- otherwise keep the more of leaving it and taking it, with the best for the room it leavesPython lines 15 and 16
- the last cell is the most the bag holds; reading back, a cell worth more than the one above took its itemPython line 17
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
def knapsack(items, capacity):
"""The most value a bag that holds capacity can carry, each item whole or left out.
items is a list of (weight, value) pairs, each a whole number from 1 up,
and capacity is a whole number from 0. Returns the most value.
"""
n = len(items)
# best[i][c]: the most value the first i items carry in a room of c
best = [[0] * (capacity + 1) for _ in range(n + 1)] # no items or no room: 0
for i in range(1, n + 1): # each item, in turn
weight, value = items[i - 1]
for c in range(1, capacity + 1): # each room from 1 up
if weight > c: # too heavy for this room
best[i][c] = best[i - 1][c] # keep the cell above
else: # the more of leaving it and taking it
best[i][c] = max(best[i - 1][c], value + best[i - 1][c - weight])
return best[n][capacity] # the last cell
how it scales
The plot counts the cells the method fills for the watch page's 3 items, in a bag that holds , measured from 10 to 100,000.
Each mark across or up is ten times the one before. The line climbs one mark up for each mark across: 300 cells at 100 and 3,000 at 1,000: ten times the room, ten times the cells. Here the cost is the cells, and a slope of 1 means they grow as , as section 4's question 1 derives. Twice the room makes twice the cells.
cells filled, ten times more at each mark up
, how much weight the bag holds, ten times more at each mark to the right
- 3 items in a bag that holds , whatever their weights and valuessolid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times W, 10 times the work
| cells filled | time | |
|---|---|---|
| 1,000 | 3,000 | about 3 microseconds |
| 100,000 | 300,000 | about 300 microseconds |
| 10,000,000 | 30,000,000 | about 30 milliseconds |
The cells filled are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
"""Count the knapsack's cells yourself, as the plot on this page does.
Run it with Python 3.12 or later. For each room W from 10 to 100,000 it
prints the cells the method fills for the watch page's 3 items in a bag
that holds W. The counts are the same on any computer, whatever the
weights and values; only the time differs.
"""
def knapsack(items, capacity):
"""The most value a bag that holds capacity can carry, each item whole or left out.
items is a list of (weight, value) pairs, each a whole number from 1 up,
and capacity is a whole number from 0. Returns the most value.
"""
n = len(items)
# best[i][c]: the most value the first i items carry in a room of c
best = [[0] * (capacity + 1) for _ in range(n + 1)] # no items or no room: 0
for i in range(1, n + 1): # each item, in turn
weight, value = items[i - 1]
for c in range(1, capacity + 1): # each room from 1 up
if weight > c: # too heavy for this room
best[i][c] = best[i - 1][c] # keep the cell above
else: # the more of leaving it and taking it
best[i][c] = max(best[i - 1][c], value + best[i - 1][c - weight])
return best[n][capacity] # the last cell
def count(items, capacity):
"""How many cells the method fills: each item makes a row, with one
cell for each room from 1 to capacity, whatever the weights and values."""
cells = 0
for _ in items: # a row for each item
cells += capacity # a cell in it for each room from 1 up
return cells
# The watch page's first example's items, each (weight, value).
ITEMS = [(4, 50), (2, 30), (3, 40)]
if __name__ == "__main__":
print(f"{'W':>7} {'cells':>12}")
for W in (10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10_000, 20_000, 50_000, 100_000):
print(f"{W:>7} {count(ITEMS, W):>12}")
best, worst and average
Best, worst and average usually name different inputs of one size. Here the size is , what the bag holds, and this page keeps 3 items. Then every bag fills the same cells, whatever the weights and values. So the table has one column, under the name worst, and no average is worked out. In the grid below, from 1 up means for any of 1 or more.
A case is one kind of input: here, which items. A bound says how fast its cost grows as the room grows.
The counts are in the grid below. A count is often made of pieces that grow at different speeds, and the fastest-growing piece swamps the rest. With its first row and column, the table holds numbers, as question 2 works out: at a room of 1,000, 4,000 plus 4, and the 4 hardly matters. So how a cost grows is what tells one method from another, and the bounds keep just that.
| worst3 items in a bag that holds , whatever their weights and values | |
|---|---|
| cells filled | , from 1 up |
| how the cells filled grow in each case | |
| tight, | |
| ceiling, | |
| floor, | |
extra memory: A table of one number for each row and each room, or one row for the most value alone.
Extra memory is the room it needs on top of the input itself, while it runs.
| items | room | cells | most value |
|---|---|---|---|
| 4 50, 2 30, 3 40 | 4 | 12 | 50 |
| 1 10, 1 20, 1 30 | 4 | 12 | 60 |
| 5 20, 6 30, 7 40 | 4 | 12 | 0 |
| W | cells | numbers held |
|---|---|---|
| 1 | 3 | 8 |
| 2 | 6 | 12 |
| 5 | 15 | 24 |
| 8 | 24 | 36 |
| 100 | 300 | 404 |
| 1,000 | 3,000 | 4,004 |
where the formula comes from
Five questions, each worked line by line. Question 1 is the count the plot draws.
the move: a row for each item
the line:order 0 1 2 3 - given given given given A given 1 2 3 B given 4 5 6 C given 7 8 9 Three items in a room of 3, each cell numbered in the order it is filled, row by row. Given cells are written first, not counted. 3 rows of 3, 9 cells. why it is allowed: Each item has a row, and each row fills one cell for each room from 1 to . The watch page's 3 items in a room of 5 fill 3 times 5, 15 cells.
the move: keep 3 items
the line:why it is allowed: This page keeps 3 items, so is 3, and 3 times is written . When is 3, 9.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 2, as a number is at most itself.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 3, with the fixed multiple 3. reads is in, and means at most a fixed multiple of , from some on.
guess it, thenthe move: a floor
the line:why it is allowed: By line 2, as a number is at least itself.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 5, with the fixed multiple 3. means at least a fixed multiple of , above 0, from some on.
guess it, thenthe move: both together
the line:why it is allowed: Lines 4 and 6 bound by the same growth. means both.
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: count the rows and columns
the line:item 0 1 2 3 - 0 0 0 0 A 0 0 0 25 B 0 15 15 25 C 0 15 20 35 Section 5's items, A weighing 3 and worth 25, B 1 and 15, and C 2 and 20, in a room of 3. 4 rows of 4 numbers, 16 in all. The first row and column count, though no step fills them. why it is allowed: A row for no items, then one for each of the 3 items, so 4 rows. A column for each room from 0 to , so . When is 3, 4 times 4, which is 16.
the move: multiply out
the line:why it is allowed: 4 lots of , and 4 lots of 1. When is 3, 12 + 4, which is 16.
guess it, thenthe move: a ceiling
the line:why it is allowed: From 1 up, 4 is at most . Add to both, and is at most 8 lots of . When is 3, 16 is at most 24.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 3, with the fixed multiple 8.
guess it, thenthe move: a floor
the line:why it is allowed: By line 2: take 4 away from , and is left, which is less. When is 3, 16 is at least 12.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 5, with the fixed multiple 4.
guess it, thenthe move: both together
the line:why it is allowed: Lines 4 and 6 bound by the same growth.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: what a cell reads
the line:why it is allowed: Leaving the item reads the cell above. Taking it reads the row above, at the room it leaves. So once a row is full, the rows above it are never read again.
the move: write over one row, from the right
the line:row 1 2 3 4 5 after A 0 0 0 50 50 B, from the right 0 30 30 50 50 B, from the left 0 30 30 60 60 B's numbers written over A's, on the watch page's first example, rooms 1 to 5. From the right, room 4 reads room 2 while it still holds A's 0, and keeps 50. From the left, room 2 already holds B's 30, so room 4 takes B twice, 60, which is wrong. why it is allowed: Write each item's numbers over the item before's, starting at room . A cell reads its own room and the room its item leaves, to its left. From the right, neither is written yet, so both still hold the row above. Filled from the left, the smaller room is already new, and an item could go in twice, as the books show (volume three, chapter 39).
guess it, thenthe move: one row
the line:why it is allowed: So the row holds one number for each room from 0 to . When is 3, 4 numbers, against the table's 16.
guess it, thenthe move: but not the items
the line:why it is allowed: Reading back compares a cell with the one above it, in every row from the last up. One row has written over them, so it gives the most value, not which items, as the books note (volume three, chapter 39).
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: the promise
the line:why it is allowed: A cell's row allows the items from A down to its own, and its column gives a room. This is what to prove. Lines 2 to 8 prove it, cell by cell, in the order the cells are filled.
the move: it starts right
the line:why it is allowed: With no items, or no room, nothing goes in, so the most is 0, as written.
guess it, thenthe move: suppose so far
the line:row reads right by no items nothing line 2 A the row with no items line 2 at room 0, lines 4 to 7 after B row A line 2 at room 0, lines 4 to 7 after C row B line 2 at room 0, lines 4 to 7 after Each row reads only the row above it, so being right passes down, row by row, from the row with no items. why it is allowed: Rows fill from the top, so the cells a cell reads, in the row above, are written or filled before it. Suppose each of those holds the most. This is fair. Line 2 starts it, and lines 4 to 7 show the cell is then right too. Line 8 carries that to every cell, in the order they are filled.
guess it, thenthe move: two kinds of load
the line:why it is allowed: A load is a set of the row's items whose weights add up to at most the room. Either it leaves the row's own item out, or it takes it.
guess it, thenthe move: leaving it
the line:why it is allowed: Without its item, the load uses only the items above, in the same room. By line 3, the cell above holds the most such a load is worth.
guess it, thenthe move: taking it
the line:why it is allowed: With its item, the rest uses only the items above, and weighs at most the room less the item's weight. By line 3, that cell in the row above holds the most the rest is worth. An item heavier than the room cannot be taken at all, so then every load leaves it.
guess it, thenthe move: so the cell is right
the line:C in room 5 reads worth leave C the cell above, room 5 50 take C 40 + the row above, room 2 70 The two choices for the last cell of the watch page's first example. The more is 70, and no load of A, B and C in room 5 is worth more. why it is allowed: By lines 5 and 6, no load is worth more than the more of the two. Both can be packed: the cell above's load, or the row above's load at the room left plus this item, which fits. So the more of the two is the most, and it is what the rule writes. For C in room 5: leaving C keeps 50, and taking it is 40 + 30, which is 70, so 70. For an item too heavy, the rule copies the cell above, the most by lines 5 and 6, as every load leaves it.
guess it, thenthe move: every cell
the line:why it is allowed: By line 2, the first row and column are. By lines 3 to 7, each later cell is right once those before it are. So, filled in order, every cell is, the last included.
guess it, thenthe move: count them
the line:why it is allowed: Every number the table holds, each right by line 8: the same count as question 2's . When is 3, 16.
guess it, then
try it with a small : at , line 9 gives , which you can work out by hand
the move: the smallest of d digits
the line:d smallest W cells 3 times d 1 1 3 3 2 10 30 6 3 100 300 9 4 1,000 3,000 12 7 1,000,000 3,000,000 21 The watch page's 3 items in the smallest bag of digits. One digit more, and the cells are 10 times as many. Beside them, 3 times , a cost that grows with the length in digits, adds only 3. why it is allowed: A number of digits starts with a digit of 1 or more, and digits follow. The smallest is 1 and then zeros. For 3 digits, 100.
the move: write it as a power
the line:why it is allowed: 1 and then zeros is tens multiplied together, written . For 1 digit there are no tens to multiply, which leaves 1. For 3 digits, 100.
guess it, thenthe move: its cells
the line:why it is allowed: By question 1 of section 4, the cells are 3 times the room. So by line 2, the smallest of digits fills : that is . For 3 digits, 300.
guess it, thenthe move: every room of d digits
the line:why it is allowed: By line 1, every such is at least the smallest. By question 1 of section 4, a bigger fills more cells, , so is the fewest.
guess it, thenthe move: each digit more
the line:why it is allowed: One digit more multiplies by one more 10, so grows 10 times with each digit. Against the room, the cells grow in a straight line, . Against its length in digits, the fewest grow tenfold a digit, and 7 digits, a bag of 1,000,000, already make 3,000,000 cells. A cost like this is called pseudo-polynomial.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
count it yourself
Three items, each written weight then value, in a bag that holds 3, the number after the semicolon. Step by step, each cell filled adds 1 to the count on its own step.
| step | what happens | cells filled |
|---|---|---|
| 1 | Pack a bag that holds 3 with the most value from 3 items. With no items or no room it holds nothing, so the first row and column are 0. | 0 |
| 2 | Item A weighs 3, more than the room of 1, so it cannot go in. Keep 0 from the cell above. | 1 |
| 3 | Item A weighs 3, more than the room of 2, so it cannot go in. Keep 0 from the cell above. | 2 |
| 4 | With room 3, leaving A out keeps 0. Taking it is worth 25, plus 0 for the room it leaves: 25. Taking it is better, so write 25. | 3 |
| 5 | With room 1, leaving B out keeps 0. Taking it is worth 15, plus 0 for the room it leaves: 15. Taking it is better, so write 15. | 4 |
| 6 | With room 2, leaving B out keeps 0. Taking it is worth 15, plus 0 for the room it leaves: 15. Taking it is better, so write 15. | 5 |
| 7 | With room 3, leaving B out keeps 25. Taking it is worth 15, plus 0 for the room it leaves: 15. That is no better, so leave it and write 25. | 6 |
| 8 | Item C weighs 2, more than the room of 1, so it cannot go in. Keep 15 from the cell above. | 7 |
| 9 | With room 2, leaving C out keeps 15. Taking it is worth 20, plus 0 for the room it leaves: 20. Taking it is better, so write 20. | 8 |
| 10 | With room 3, leaving C out keeps 25. Taking it is worth 20, plus 15 for the room it leaves: 35. Taking it is better, so write 35. | 9 |
| 11 | Done: take B and C, weighing 3 in all and worth 35, the most the bag holds. The marked cells are where each item went in. | 9 |
In all, 9 cells filled. The formula from section 4, , gives at : the same.
where you meet it
The problem is old. George Dantzig's 1957 paper on such problems already treats it as known, as the books note (volume three, chapter 39).
Packing with a solver
Google's free OR-Tools library has a knapsack solver. One of the methods you can pick in it is a dynamic programming solver. It fills one row of rooms from the biggest room down, as section 4's question 3 does.
source: Google OR-Tools, the reference for its knapsack solver (opens in a new tab) and its dynamic programming code (opens in a new tab)
A secret code that broke
In 1978, Ralph Merkle and Martin Hellman built a way to send secret messages on a knapsack where each item's value is its weight: which items make this exact total? Adi Shamir broke its basic form in 1982.
source: R. C. Merkle and M. E. Hellman, IEEE Transactions on Information Theory 24, 1978, Hiding information and signatures in trapdoor knapsacks (opens in a new tab) and A. Shamir, 23rd Symposium on Foundations of Computer Science, 1982, A polynomial time algorithm for breaking the basic Merkle-Hellman cryptosystem (opens in a new tab)
Budgets and sprints
Choosing projects that fit a budget, or features that fit a sprint of so many days, is this problem, as the books note. A team that takes the most valuable first can take 50 when 70 fits, as section 1 shows.
source: the books' volume three, chapter 39
what is used instead
When the room is a huge number, or is measured very finely, the table is too big. Solvers then search the sets of items, cutting off any that cannot beat the best found so far. Where an item can be split, taking the most value per weight first is exactly right, as the books note (volume three, chapter 39).
how it compares
The plain method asks the same question as calls, with no table: leave the last item, or take it where it fits. The 10 items below weigh 1 to 10, 55 in all. In a room of 55 or more, every item fits, so each call with an item left asks 2 more, one level for each of the 10 items. That makes 1 + 2 + 4 + ... + 1,024 calls, the last 2 multiplied together 10 times, which is 2,047, in both rooms below. A memo keeps each answer once worked out, as the page on solving each smaller problem once shows, and reaches only the rooms some set of items leaves. The table fills every room, so its cells grow with , and one row is enough for the answer alone. Coin change fills a row of amounts too, but there a coin can be used again, as filling from the left allows.
| way | room 100 | room 100,000 |
|---|---|---|
| plain method | 2,047 calls | 2,047 calls |
| with a memo | 481 calls | 481 calls |
| the table | 1,000 cells | 1,000,000 cells |
| one row | 955 cells | 999,955 cells |