Skip to content

Knapsack from the top down

planning ahead

Level 2 of 3

Also called 0/1 knapsack, memoised and Top-down dynamic programming.

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.

item12345
none00000
A-00-50
B-30--50
C----70
The cells the method works out on the watch page's first example. The row of no items holds 0 from the start, as room 0 does in every row, which is not drawn. A dash is a cell never asked for. 6 cells of the table's 15, rooms 1 to 5 in rows A to C, and the last holds 70.
cellasks forholds
C at room 5B at 5, and B at 270
B at 5A at 5, and A at 350
B at 2A at 2, and A at 030
A at 5no items at 5, and at 150
A at 3no items at 3: A is too heavy0
A at 2no items at 2: A is too heavy0
Each cell asks the row above for the room it keeps without its item and, when the item fits, for the room the item leaves. A row of no items, or a room of 0, holds 0.
The most valuable first is not best: 8 moments of its 18 steps, the steps between them left for the watch page
  1. step 1 of 18

    012345ABC000000000C5

    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

    watch from here

  2. step 2 of 18

    012345ABC000000000C5B5

    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

    watch from here

  3. step 5 of 18

    012345ABC000000000C5B5A5

    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.

    watch from here

  4. step 6 of 18

    012345ABC00000005000C5B5

    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

    watch from here

  5. step 9 of 18

    012345ABC000000005000C5B5

    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

    watch from here

  6. step 15 of 18

    012345ABC000000000500500C5B2

    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

    watch from here

  7. step 17 of 18

    012345ABC0000000005003050070

    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

    watch from here

  8. step 18 of 18

    012345ABC0000000005003050070

    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.

    watch from here

the steps, in plain words
  1. 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
  2. with no items or no room, the bag holds nothing: 0Python lines 11 and 12
  3. if item i weighs more than the room, ask only for the best without it, and write thatPython lines 15, 16, 17 and 19
  4. otherwise ask for the best without it, then with it, and write the morePython lines 17, 18, 19 and 20
  5. 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 WW, 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

slope 0102101102103104105106107slope 0101102101102103104105106107slope 0101102101102103104105106107

WW, 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
how long working out the cells takes, at a billion a second
WWcells filledtime
1,0007about 7 nanoseconds
100,0007about 7 nanoseconds
10,000,0007about 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 Θ(1)\Theta(1), where the table's cells grow with WW.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
best3 items each heavier than the bag, such as items of 10 in a bag of 9worstitems weighing 1, 2 and 1, whatever the room from 4 up
cells filled33, from 1 up77, from 4 up; items of 1, 1 and 1 make 3, 5 and 6 in rooms 1, 2 and 3
times asked44, from 1 up1515, 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, Θ\ThetaΘ(1)\Theta(1)Θ(1)\Theta(1)
ceiling, OOO(1)O(1)O(1)O(1)
floor, Ω\OmegaΩ(1)\Omega(1)Ω(1)\Omega(1)

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 6cellscalls
7 10, 8 20, 7 3034
1 10, 2 20, 1 15715
4 50, 2 30, 3 40713
Three bags in a room of 6, each item written weight then value, counted by the run. The watch page's items work out the most cells, 7, but only 13 calls: A is too heavy for rooms 3 and 1.
rowitems of 1, 1 and 1items of 1, 2 and 1
C44
B4, 34, 3
A4, 3, 24, 3, 2, 1
cells67
The rooms each row is asked for in a room of 4. With three items of 1, B at 4 takes its item and asks for A at 3. B at 3 leaves its item and asks for A at 3 too. The memory answers the second ask.
Wfewestmostthe table
1333
2356
3369
43712
10037300
100,00037300,000
Cells for 3 items in a bag that holds WW. The knapsack table fills 3 times WW; this method never more than 7.

where the formula comes from

Four questions, each worked line by line. Questions 1 and 2 are the counts the plot draws.

Question 1: at most how many cells, HH, does the method work out for 3 items in a bag that holds WW, from 4 up?
  1. the move: the last row, once

    the line:
    row C: 1 room\text{row C: 1 room}

    why it is allowed: Only the first call asks for row C, at room WW. No cell asks for a cell in its own row.

  2. the move: at most twice the rooms

    the line:
    each room asks the rowabove for at most 2\begin{gathered} \text{each room asks the row} \\ \text{above for at most 2} \end{gathered}

    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.

  3. the move: light items reach it

    the line:
    weights 1, 2 and 1:rooms 1+2+4\begin{gathered} \text{weights 1, 2 and 1:} \\ \text{rooms } 1 + 2 + 4 \end{gathered}
    rowrooms asked forcells
    C41
    B4, 32
    A4, 3, 2, 14
    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.

  4. the move: add them

    the line:
    H=7H = 7

    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.

  5. the move: a ceiling

    the line:
    H≤7H \le 7

    why it is allowed: By line 4. An equals gives a ceiling and a floor at once.

  6. the move: read the bound

    the line:
    H∈O(1)H \in O(1)

    why it is allowed: By line 5: at most 7, a fixed number, whatever WW is.

  7. the move: a floor

    the line:
    H≥7H \ge 7

    why it is allowed: By line 4 again.

  8. the move: read the bound

    the line:
    H∈Ω(1)H \in \Omega(1)

    why it is allowed: By line 7: at least 7, a fixed number above 0.

  9. the move: both together

    the line:
    H∈Θ(1)H \in \Theta(1)

    why it is allowed: Lines 6 and 8 bound HH by the same growth, 1, which is to say none.

try it with a small WW: at W=4W = 4, line 4 gives H=7H = 7, which you can work out by hand

Question 2: at least how many cells, LL, does the method work out for 3 items in a bag that holds WW, from 1 up?
  1. the move: every row once

    the line:
    each row is askedfor room W\begin{gathered} \text{each row is asked} \\ \text{for room } W \end{gathered}

    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 WW, so row B is, and then row A. So at least 3 cells.

  2. the move: heavy items stop there

    the line:
    items heavier than W:one room a row\begin{gathered} \text{items heavier than } W\text{:} \\ \text{one room a row} \end{gathered}
    rowrooms asked forcells
    C41
    B41
    A41
    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.

  3. the move: the floor is reached

    the line:
    L=3L = 3

    why it is allowed: By line 1, at least 3, and by line 2 heavy items work out just 3.

  4. the move: a ceiling

    the line:
    L≤3L \le 3

    why it is allowed: By line 3.

  5. the move: read the bound

    the line:
    L∈O(1)L \in O(1)

    why it is allowed: By line 4: at most 3, a fixed number.

  6. the move: a floor

    the line:
    L≥3L \ge 3

    why it is allowed: By line 3 again.

  7. the move: read the bound

    the line:
    L∈Ω(1)L \in \Omega(1)

    why it is allowed: By line 6: at least 3, a fixed number above 0.

  8. the move: both together

    the line:
    L∈Θ(1)L \in \Theta(1)

    why it is allowed: Lines 5 and 7 bound LL by the same growth.

try it with a small WW: at W=4W = 4, line 3 gives L=3L = 3, which you can work out by hand

Question 3: with nn items, at most how many cells, MM, can the method work out, however big the bag?
  1. the move: row by row

    the line:
    rows ask for at most1,2,4,…,2n−1\begin{gathered} \text{rows ask for at most} \\ 1, 2, 4, \dots, 2^{n - 1} \end{gathered}

    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.

  2. the move: big items, big bag

    the line:
    weights 2n−1,…,2,1reach every one\begin{gathered} \text{weights } 2^{n - 1}, \dots, 2, 1 \\ \text{reach every one} \end{gathered}
    items taken below Atheir weightroom left for A
    none04
    C13
    B22
    B and C31
    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 2n−12^{n - 1} or more. The items below row A can weigh 0, 1, 2 and on, up to one less than 2n−12^{n - 1} 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.

  3. the move: add the rows

    the line:
    M=1+2+4+⋯+2n−1M = 1 + 2 + 4 + \dots + 2^{n - 1}

    why it is allowed: By lines 1 and 2, the most is every row at its most. With 3 items, 1 + 2 + 4.

  4. the move: use the doubling sum

    the line:
    M=2n−1M = 2^n - 1
    where does this come from?
    question 1 of the page doubling and halving sumsAdd 1+2+4+⋯+2n1 + 2 + 4 + \dots + 2^n. What is the total?
    1. the move: name the sum

      the line:
      S=1+2+4+⋯+2nS = 1 + 2 + 4 + \dots + 2^n

      why it is allowed: Let SS be the doubling sum up to 2n2^n. For nn as 3, it is 1 + 2 + 4 + 8.

    2. the move: double both sides

      the line:
      2S=2+4+8+⋯+2n+12S = 2 + 4 + 8 + \dots + 2^{n + 1}

      why it is allowed: Each term doubled is the next one along, and 2n2^n becomes 2n+12^{n + 1}. Doubling both sides keeps them equal. The plan: the two sums share all but their ends.

    3. the move: take line 1 away

      the line:
      2S−S=(2+4+⋯+2n+1)−(1+2+⋯+2n)\begin{aligned} 2S - S = {} & (2 + 4 + \dots + 2^{n + 1}) \\ & - (1 + 2 + \dots + 2^n) \end{aligned}

      why it is allowed: Take SS from both sides of line 2. On the right, write SS out as line 1 does.

    4. the move: tidy the left side

      the line:
      S=(2+4+⋯+2n+1)−(1+2+⋯+2n)\begin{aligned} S = {} & (2 + 4 + \dots + 2^{n + 1}) \\ & - (1 + 2 + \dots + 2^n) \end{aligned}

      why it is allowed: Two lots of SS less one lot is one lot.

    5. the move: cancel what both brackets share

      the line:
      S=2n+1−1S = 2^{n + 1} - 1
      when n is 3124816
      first bracket24816
      second bracket1248
      left overtake away 116
      Line 4 when nn is 3. The 2, 4 and 8 cancel, leaving 16 less 1, which is 15.

      why it is allowed: Every term from 2 to 2n2^n is in both brackets and cancels, leaving 2n+12^{n + 1} less 1.

    6. the move: the terms before the last

      the line:
      1+2+⋯+2n−1=2(n−1)+1−1\begin{gathered} 1 + 2 + \dots + 2^{n - 1} \\ = 2^{(n - 1) + 1} - 1 \end{gathered}

      why it is allowed: The sum of line 5 stopping one term sooner: line 5 with n−1n - 1 for nn. For 3, it is 1 + 2 + 4. At nn as 0 no terms are left, adding to 0, and 2 to the power 0, less 1, is 0 too.

    7. the move: tidy the power

      the line:
      2(n−1)+1−1=2n−12^{(n - 1) + 1} - 1 = 2^n - 1

      why it is allowed: One more than n−1n - 1 is nn. For 3, 1 + 2 + 4 is 7, one less than 8.

    8. the move: read it

      the line:
      one less thanthe next term,under twice the last\begin{gathered} \text{one less than} \\ \text{the next term,} \\ \text{under twice the last} \end{gathered}

      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 2n+12^{n + 1}, twice the last.

    the whole page: doubling and halving sums

    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 2n−12^{n - 1}, to 2n−12^n - 1. For 3 items, 1 + 2 + 4 is 7, one less than 8.

  5. the move: against the table

    the line:
    never more than thetable’s n×W\begin{gathered} \text{never more than the} \\ \text{table's } n \times W \end{gathered}

    why it is allowed: Each cell asked for is a cell of the table, so the method never works out more than n×Wn \times W: 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 WW, so a room of 524,288 or more.

try it with a small nn: at n=3n = 3, line 3 gives M=7M = 7, which you can work out by hand

Question 4: at most how many calls, KK, does the method make for 3 items in a bag that holds WW, from 4 up?
  1. the move: where calls come from

    the line:
    a call is the first ask,or an ask by a new cell\begin{gathered} \text{a call is the first ask,} \\ \text{or an ask by a new cell} \end{gathered}

    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.

  2. the move: count them

    the line:
    at most 1+2×7 calls\text{at most } 1 + 2 \times 7 \text{ calls}

    why it is allowed: By line 1 and question 1, at most 7 new cells, each asking at most twice, and the first call.

  3. the move: light items fit everywhere

    the line:
    weights 1, 2 and 1:every cell asks twice\begin{gathered} \text{weights 1, 2 and 1:} \\ \text{every cell asks twice} \end{gathered}

    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.

  4. the move: the most

    the line:
    K=15K = 15

    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.

try it with a small WW: at W=4W = 4, line 4 gives K=15K = 15, 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.

1 10, 2 20, 1 15; 4, every step written down
stepwhat happenstimes askedcells filled
1Ask 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.10
2To 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.20
3To 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.30
4With no items there is nothing to take, so room 4 holds 0, from the first row.40
5With no items there is nothing to take, so room 3 holds 0, from the first row.50
6With 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.51
7Then 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.61
8With no items there is nothing to take, so room 2 holds 0, from the first row.71
9With no items there is nothing to take, so room 1 holds 0, from the first row.81
10With 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.82
11With 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.83
12Then 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.93
13To 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.103
14With no items there is nothing to take, so room 3 holds 0, from the first row.113
15With no items there is nothing to take, so room 2 holds 0, from the first row.123
16With 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.124
17Then 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.134
18With no items there is nothing to take, so room 1 holds 0, from the first row.144
19With no items there is nothing to take, so room 0 holds 0, from the first row.154
20With 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.155
21With 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.156
22With 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.157
23Done: 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.157

In all, 7 cells filled. The formula from section 4, 1+2+41 + 2 + 4, gives H=7H = 7 at W=4W = 4: 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 WW. 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.

wayroom 100room 100,000
plain method2,047 calls2,047 calls
this method481 calls481 calls
this method240 cells240 cells
the table1,000 cells1,000,000 cells
10 items weighing 1 to 10, counted by running each way. Compare calls with calls: the memory cuts 2,047 to 481. Compare cells with cells: the table's grow with the room, and this method's 240 stay.

race them on one row of your own