Knapsack from the top down
how it works
The idea on the watch page's first example, three items and a bag that holds 5. Then the whole method on it, step by step.
A bag holds 5. Item A weighs 4 and is worth 50, B weighs 2 and is worth 30, and C weighs 3 and is worth 40. The best load is B and C, worth 70. Taking A first, the most valuable, leaves room 1, where nothing fits: only 50. The knapsack table finds it by filling all 15 cells, every item and every room. This method starts at the end. It asks for the last cell: the best of A, B and C in room 5. That cell asks two smaller questions of the row above. Leave C: the best of A and B in room 5. Take C: 40, plus the best of A and B in room 5 less 3, which is 2. Each of those asks the row above in turn. With no items or no room, the answer is 0, with no asking. Each answer is kept in a memory the first time it is worked out, so a cell asked again is read. Here only 6 cells are ever asked for, as the first picture shows. This page counts cells, one for each cell worked out: 6, as the watch page counts. The code below, in the language Python, asks from the top down and returns the last cell.
| item | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| none | 0 | 0 | 0 | 0 | 0 |
| A | - | 0 | 0 | - | 50 |
| B | - | 30 | - | - | 50 |
| C | - | - | - | - | 70 |
| cell | asks for | holds |
|---|---|---|
| C at room 5 | B at 5, and B at 2 | 70 |
| B at 5 | A at 5, and A at 3 | 50 |
| B at 2 | A at 2, and A at 0 | 30 |
| A at 5 | no items at 5, and at 1 | 50 |
| A at 3 | no items at 3: A is too heavy | 0 |
| A at 2 | no items at 2: A is too heavy | 0 |
step 1 of 18
Ask for the most value 3 items can put in a bag that holds 5. With no items or no room it holds nothing, so the first row and column are 0. Every other cell stays empty until it is asked for.
what it remembers to know where it is
- item
- C
- room
- 5
step 2 of 18
To decide on C with room 5, first ask for the best without it: the items up to B, room 5. That cell is empty, so it has to be worked out.
what it remembers to know where it is
- item
- B
- room
- 5
step 5 of 18
With no items there is nothing to take, so room 1 holds 0, from the first row.
what it remembers to know where it is
- item
- not yet
- room
- 1
Where it says not yet, nothing is held there at that moment.
step 6 of 18
With room 5, 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
- 5
step 9 of 18
Item A weighs 4, more than the room of 3, so it cannot go in. Write 0, the best without it.
what it remembers to know where it is
- item
- A
- room
- 3
step 15 of 18
With no room, the items up to A hold nothing: 0, from the first column.
what it remembers to know where it is
- item
- A
- room
- 0
step 17 of 18
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 18 of 18
Done: take B and C, weighing 5 in all and worth 70, the most the bag holds. It asked for 6 of the table's 15 cells; 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
- ask for the best of the items up to i with room c: if the memory has it, the answer is therePython lines 8, 10, 13 and 14
- with no items or no room, the bag holds nothing: 0Python lines 11 and 12
- if item i weighs more than the room, ask only for the best without it, and write thatPython lines 15, 16, 17 and 19
- otherwise ask for the best without it, then with it, and write the morePython lines 17, 18, 19 and 20
- the cell for every item and the whole bag is the answer; reading back, a cell worth more than the one above took its itemPython line 22
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_memo(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, asking
only for the cells it needs, each worked out once.
"""
memo = {} # (i, c): the most value the first i items carry in a room of c
def best(i, c):
if i == 0 or c == 0: # no items or no room
return 0
if (i, c) in memo: # worked out before
return memo[(i, c)]
weight, value = items[i - 1]
answer = best(i - 1, c) # leave item i out
if weight <= c: # it fits, so try taking it
answer = max(answer, value + best(i - 1, c - weight))
memo[(i, c)] = answer # keep it for the next ask
return answer
return best(len(items), capacity) # every item, the whole bag
how it scales
The plot counts the cells the method works out for 3 items in a bag that holds , measured from 10 to 100,000. Two cases: items too heavy for the bag, the fewest, and items weighing 1, 2 and 1, the most, both drawn in section 3.
Each mark across or up is ten times the one before. Both lines lie flat: the most stays 7 from a room of 10 to 100,000, and the fewest stays 3. Ten times the room gives the same cells: a flat line, a slope of 0. The knapsack table's cells grow ten times when the room does, which its page draws as a slope of 1.
cells filled, ten times more at each mark up
, how much weight the bag holds, ten times more at each mark to the right
- items weighing 1, 2 and 1, whatever the room from 4 upsolid where measured by running it; dashed where its formula carries it on to ten millionslope 0: ten times W, 1 times the work
- 3 items each heavier than the bag, such as items of 10 in a bag of 9solid where measured by running it; dashed where its formula carries it on to ten million
| cells filled | time | |
|---|---|---|
| 1,000 | 7 | about 7 nanoseconds |
| 100,000 | 7 | about 7 nanoseconds |
| 10,000,000 | 7 | about 7 nanoseconds |
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 from the top down 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 works out for 3 items too heavy for the bag,
the fewest, and for items weighing 1, 2 and 1, the most. The counts are
the same on any computer, whatever the values; only the time differs.
"""
def knapsack_memo(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, asking
only for the cells it needs, each worked out once.
"""
memo = {} # (i, c): the most value the first i items carry in a room of c
def best(i, c):
if i == 0 or c == 0: # no items or no room
return 0
if (i, c) in memo: # worked out before
return memo[(i, c)]
weight, value = items[i - 1]
answer = best(i - 1, c) # leave item i out
if weight <= c: # it fits, so try taking it
answer = max(answer, value + best(i - 1, c - weight))
memo[(i, c)] = answer # keep it for the next ask
return answer
return best(len(items), capacity) # every item, the whole bag
def count(items, capacity):
"""How many cells the method works out: the cells its memory holds at the end,
as each cell is worked out once and then kept."""
memo = set()
def ask(i, c):
if i == 0 or c == 0 or (i, c) in memo: # answered with no work
return
weight = items[i - 1][0]
ask(i - 1, c) # without item i
if weight <= c: # with it, when it fits
ask(i - 1, c - weight)
memo.add((i, c))
ask(len(items), capacity)
return len(memo)
def heavy(W):
"""3 items each heavier than the bag, each (weight, value)."""
return [(W + 1, 10), (W + 1, 20), (W + 1, 30)]
# Items weighing 1, 2 and 1, each (weight, value).
LIGHT = [(1, 10), (2, 20), (1, 15)]
if __name__ == "__main__":
print(f"{'W':>7} {'fewest':>8} {'most':>8}")
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(heavy(W), W):>8} {count(LIGHT, W):>8}")
best, worst and average
Items too heavy to go in cost the fewest cells: each row is asked for the whole bag alone. Items whose every choice leaves a different room cost the most, as weights 1, 2 and 1 do from a room of 4. Three items of 1 cost only 6, as two choices leave the same room. Other items fall between, so the average depends on which items are chosen.
A case is one kind of input: here, which items. A bound says how fast its cost grows as the room grows.
Here no piece of the count grows with the room: 7 cells at a room of 4 and at 4 million. So the bounds are , where the table's cells grow with .
| best3 items each heavier than the bag, such as items of 10 in a bag of 9 | worstitems weighing 1, 2 and 1, whatever the room from 4 up | |
|---|---|---|
| cells filled | , from 1 up | , from 4 up; items of 1, 1 and 1 make 3, 5 and 6 in rooms 1, 2 and 3 |
| times asked | , from 1 up | , from 4 up; items of 1, 1 and 1 make 7, 11 and 13 in rooms 1, 2 and 3 |
| how the cells filled grow in each case | ||
| tight, | ||
| ceiling, | ||
| floor, | ||
extra memory: the cells asked for, at most the whole table, and the calls still waiting, at most one for each item
Extra memory is the room it needs on top of the input itself, while it runs.
| items in a room of 6 | cells | calls |
|---|---|---|
| 7 10, 8 20, 7 30 | 3 | 4 |
| 1 10, 2 20, 1 15 | 7 | 15 |
| 4 50, 2 30, 3 40 | 7 | 13 |
| row | items of 1, 1 and 1 | items of 1, 2 and 1 |
|---|---|---|
| C | 4 | 4 |
| B | 4, 3 | 4, 3 |
| A | 4, 3, 2 | 4, 3, 2, 1 |
| cells | 6 | 7 |
| W | fewest | most | the table |
|---|---|---|---|
| 1 | 3 | 3 | 3 |
| 2 | 3 | 5 | 6 |
| 3 | 3 | 6 | 9 |
| 4 | 3 | 7 | 12 |
| 100 | 3 | 7 | 300 |
| 100,000 | 3 | 7 | 300,000 |
where the formula comes from
Four questions, each worked line by line. Questions 1 and 2 are the counts the plot draws.
the move: the last row, once
the line:why it is allowed: Only the first call asks for row C, at room . No cell asks for a cell in its own row.
the move: at most twice the rooms
the line:why it is allowed: A new cell asks for the room it keeps without its item and, when the item fits, the room the item leaves. A cell asked again asks for nothing. So row B is asked for at most 2 rooms, and row A for at most 4.
guess it, thenthe move: light items reach it
the line:row rooms asked for cells C 4 1 B 4, 3 2 A 4, 3, 2, 1 4 Items weighing 1, 2 and 1 in a room of 4. Each row holds twice the rooms of the row below, 7 cells in all. why it is allowed: C at the bag's room asks row B for that room and 1 less. B weighs 2 and fits both from a room of 3 up. So each asks row A for its room and 2 less: 4 different rooms, all 1 or more from 4 up. In a room of 4: B at 4 and 3, then A at 4, 2, 3 and 1.
guess it, thenthe move: add them
the line:why it is allowed: By lines 1 and 2, at most 1 + 2 + 4, which is 7, and by line 3 items of 1, 2 and 1 work out all 7. For a room of 4 or 4 million, 7.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 4. An equals gives a ceiling and a floor at once.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 5: at most 7, a fixed number, whatever is.
guess it, thenthe move: a floor
the line:why it is allowed: By line 4 again.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 7: at least 7, a fixed number above 0.
guess it, thenthe move: both together
the line:why it is allowed: Lines 6 and 8 bound by the same growth, 1, which is to say none.
guess it, then
try it with a small : at , line 4 gives , which you can work out by hand
the move: every row once
the line:why it is allowed: A new cell always asks the row above for its own room, without its item. Row C is asked for room , so row B is, and then row A. So at least 3 cells.
the move: heavy items stop there
the line:row rooms asked for cells C 4 1 B 4 1 A 4 1 Items weighing 5, 5 and 5 in a room of 4. One cell a row, 3 in all. why it is allowed: No item fits, so no cell asks for a second room. In a room of 4, items weighing 5 ask for room 4 in each row, and nothing more.
guess it, thenthe move: the floor is reached
the line:why it is allowed: By line 1, at least 3, and by line 2 heavy items work out just 3.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 3.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 4: at most 3, a fixed number.
guess it, thenthe move: a floor
the line:why it is allowed: By line 3 again.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 6: at least 3, a fixed number above 0.
guess it, thenthe move: both together
the line:why it is allowed: Lines 5 and 7 bound by the same growth.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: row by row
the line:why it is allowed: By question 1's lines 1 and 2, the last row is asked for 1 room, and each row above for at most twice the row below. With 3 items, 1, 2 and 4.
the move: big items, big bag
the line:items taken below A their weight room left for A none 0 4 C 1 3 B 2 2 B and C 3 1 Items weighing 4, 2 and 1 in a room of 4. Each choice of B and C takes a different weight, so row A is asked for 4 different rooms. With 1 room in row C and 2 in row B, 1 + 2 + 4, which is 7 cells. why it is allowed: From the last item, weights 1, 2, 4 and on, in a bag of or more. The items below row A can weigh 0, 1, 2 and on, up to one less than in all, each total in just one way. So no room is asked twice, and each is at least 1. B, C and the rest fit every room they are asked for, so each of their cells asks twice; A's asks reach only the row of no items. With 3 items weighing 4, 2 and 1, a room of 4 is enough.
guess it, thenthe move: add the rows
the line:why it is allowed: By lines 1 and 2, the most is every row at its most. With 3 items, 1 + 2 + 4.
guess it, thenthe move: use the doubling sum
the line:where does this come from?
question 1 of the page doubling and halving sumsAdd . What is the total? the move: name the sum
the line:why it is allowed: Let be the doubling sum up to . For as 3, it is 1 + 2 + 4 + 8.
the move: double both sides
the line:why it is allowed: Each term doubled is the next one along, and becomes . Doubling both sides keeps them equal. The plan: the two sums share all but their ends.
the move: take line 1 away
the line:why it is allowed: Take from both sides of line 2. On the right, write out as line 1 does.
the move: tidy the left side
the line:why it is allowed: Two lots of less one lot is one lot.
the move: cancel what both brackets share
the line:when n is 3 1 2 4 8 16 first bracket 2 4 8 16 second bracket 1 2 4 8 left over take away 1 16 Line 4 when is 3. The 2, 4 and 8 cancel, leaving 16 less 1, which is 15. why it is allowed: Every term from 2 to is in both brackets and cancels, leaving less 1.
the move: the terms before the last
the line:why it is allowed: The sum of line 5 stopping one term sooner: line 5 with for . For 3, it is 1 + 2 + 4. At as 0 no terms are left, adding to 0, and 2 to the power 0, less 1, is 0 too.
the move: tidy the power
the line:why it is allowed: One more than is . For 3, 1 + 2 + 4 is 7, one less than 8.
the move: read it
the line:why it is allowed: By lines 6 and 7, the terms before the last add to one less than it: the last outweighs them all. By line 5 the sum is under , twice the last.
why it is allowed: The box under this line shows a doubling sum from 1 is one less than its next term. Its lines 6 and 7 take this sum, ending at , to . For 3 items, 1 + 2 + 4 is 7, one less than 8.
guess it, thenthe move: against the table
the line:why it is allowed: Each cell asked for is a cell of the table, so the method never works out more than : in a small bag that is the tighter limit. With 20 items, never more than 1,048,575. Reaching it needs row A's 524,288 different rooms, each from 1 to , so a room of 524,288 or more.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: where calls come from
the line:why it is allowed: The first call asks for the last cell. Every other call is asked by a cell being worked out, and a new cell makes at most 2.
the move: count them
the line:why it is allowed: By line 1 and question 1, at most 7 new cells, each asking at most twice, and the first call.
guess it, thenthe move: light items fit everywhere
the line:why it is allowed: Rows C and A weigh 1, which fits every room of 1 or more. Row B is asked for the bag's room and 1 less, both 2 or more from 3 up. In a room of 4, 1 + 2 times 7.
guess it, thenthe move: the most
the line:why it is allowed: By line 2, at most 15. By line 3, items of 1, 2 and 1 make every ask. For a room of 4 or 4 million, 15.
guess it, then
try it with a small : at , line 4 gives , which you can work out by hand
count it yourself
Three items, each written weight then value, in a bag that holds 4, the number after the semicolon: weights 1, 2 and 1, so the most cells. Step by step, each cell worked out adds 1 to the count on its own step.
| step | what happens | times asked | cells filled |
|---|---|---|---|
| 1 | Ask for the most value 3 items can put in a bag that holds 4. With no items or no room it holds nothing, so the first row and column are 0. Every other cell stays empty until it is asked for. | 1 | 0 |
| 2 | To decide on C with room 4, first ask for the best without it: the items up to B, room 4. That cell is empty, so it has to be worked out. | 2 | 0 |
| 3 | To decide on B with room 4, first ask for the best without it: the items up to A, room 4. That cell is empty, so it has to be worked out. | 3 | 0 |
| 4 | With no items there is nothing to take, so room 4 holds 0, from the first row. | 4 | 0 |
| 5 | With no items there is nothing to take, so room 3 holds 0, from the first row. | 5 | 0 |
| 6 | With room 4, leaving A out keeps 0. Taking it is worth 10, plus 0 for the room it leaves: 10. Taking it is better, so write 10. | 5 | 1 |
| 7 | Then ask for the best with B: it weighs 2, leaving room 2 for the items up to A. That cell is empty, so it has to be worked out. | 6 | 1 |
| 8 | With no items there is nothing to take, so room 2 holds 0, from the first row. | 7 | 1 |
| 9 | With no items there is nothing to take, so room 1 holds 0, from the first row. | 8 | 1 |
| 10 | With room 2, leaving A out keeps 0. Taking it is worth 10, plus 0 for the room it leaves: 10. Taking it is better, so write 10. | 8 | 2 |
| 11 | With room 4, leaving B out keeps 10. Taking it is worth 20, plus 10 for the room it leaves: 30. Taking it is better, so write 30. | 8 | 3 |
| 12 | Then ask for the best with C: it weighs 1, leaving room 3 for the items up to B. That cell is empty, so it has to be worked out. | 9 | 3 |
| 13 | To decide on B with room 3, first ask for the best without it: the items up to A, room 3. That cell is empty, so it has to be worked out. | 10 | 3 |
| 14 | With no items there is nothing to take, so room 3 holds 0, from the first row. | 11 | 3 |
| 15 | With no items there is nothing to take, so room 2 holds 0, from the first row. | 12 | 3 |
| 16 | With room 3, leaving A out keeps 0. Taking it is worth 10, plus 0 for the room it leaves: 10. Taking it is better, so write 10. | 12 | 4 |
| 17 | Then ask for the best with B: it weighs 2, leaving room 1 for the items up to A. That cell is empty, so it has to be worked out. | 13 | 4 |
| 18 | With no items there is nothing to take, so room 1 holds 0, from the first row. | 14 | 4 |
| 19 | With no items there is nothing to take, so room 0 holds 0, from the first row. | 15 | 4 |
| 20 | With room 1, leaving A out keeps 0. Taking it is worth 10, plus 0 for the room it leaves: 10. Taking it is better, so write 10. | 15 | 5 |
| 21 | With room 3, leaving B out keeps 10. Taking it is worth 20, plus 10 for the room it leaves: 30. Taking it is better, so write 30. | 15 | 6 |
| 22 | With room 4, leaving C out keeps 30. Taking it is worth 15, plus 30 for the room it leaves: 45. Taking it is better, so write 45. | 15 | 7 |
| 23 | Done: take A, B and C, weighing 4 in all and worth 45, the most the bag holds. It asked for 7 of the table's 12 cells; the marked cells are where each item went in. | 15 | 7 |
In all, 7 cells filled. The formula from section 4, , gives at : the same.
where you meet it
Asking from the top down and keeping each answer is how many programs avoid working the same thing out twice.
A memory built into Python
Python comes with this memory ready-made, called cache, in a part of Python called functools. Each answer is kept by what was asked, so a second ask reads it at once. That is this page's memory, kept for you.
source: the Python documentation, the functools module, its cache, which is lru_cache with no limit on its size
Measuring finely
The books pack a depot's 24 jobs, each a whole number of cubic metres, into one van of 100 cubic metres. The van is measured five times, each in units ten times finer, from 100 units to 1,000,000. The whole table grows ten thousandfold. Asked from the top down, the jobs reach the same 1,680 cells every time.
source: the books' volume three, chapter 39
what is used instead
With many items whose weights leave different rooms, the memory grows toward the whole table. The calls still waiting pile up too, one for each item, as the steps in section 1 show. C at 5 waits on B at 5, which waits on A at 5. Then the knapsack table, filled row by row, is used instead.
how it compares
Without the memory, a cell asked twice is worked out twice: call that the plain method. The knapsack table fills every cell, so its cells grow with . This method keeps a memory and asks only what the answer needs. Below, 10 items weighing 1 to 10, in that order, counted by running each.
| way | room 100 | room 100,000 |
|---|---|---|
| plain method | 2,047 calls | 2,047 calls |
| this method | 481 calls | 481 calls |
| this method | 240 cells | 240 cells |
| the table | 1,000 cells | 1,000,000 cells |