0/1 knapsack
Each item is taken whole or not at all, which is what the 0/1 means. Consider the items one at a time and every capacity from nothing up to the limit. For each pair there are exactly two possibilities: leave this item, which is the answer for the same capacity one row up; or take it, which is its value plus the answer one row up for the capacity that is left over. The better of the two goes in the cell.
Its recurrence
K(i, w) = max( K(i−1, w), value(i) + K(i−1, w − weight(i)) )
When it is the right choice
Any allocation with a hard limit and indivisible choices: which features fit in a release, which jobs fit in a budget, which files fit on a disc. The fact that it is O(n · W) rather than polynomial in the size of the input is worth knowing — the capacity is a number, and a number written down takes only log W digits, which is what makes this problem NP-hard in the strict sense and this algorithm merely useful.
How it works
- Make a table with one row per item plus a row for "no items", and one column per capacity from 0 up to the limit.
- Fill the first row and the first column with zeroes: no items, or no room, is worth nothing.
- For each item and each capacity, read the cell directly above — that is leaving the item.
- If the item fits, also read the cell one row up and its weight to the left, and add the item’s value — that is taking it.
- Write the better of the two, and remember which it was.
- Walk back from the bottom-right: wherever the value differs from the cell above, that item was taken.
Worth noticing
- The two arrows do not point at the same distance. "Leave" is always the cell directly above; "take" reaches left by exactly this item’s weight, so the arrow’s length is the weight — the input is visible in the shape of the picture.
- An item heavier than the current capacity has only one option, and the page draws that: one arrow instead of two, with the refused one marked as refused.
- The traceback is where the answer actually is. The bottom-right cell says what the best load is worth; only the walk back says which items make it up, and two different sets of items can be worth the same.
Cost
- Best
- O(n · W)
- Average
- O(n · W)
- Worst
- O(n · W)
- Extra space
- O(n · W)
- Table
- two dimensions
- Accepts
- 1 to 8 items, each from 1 to 12; capacity from 1 to 24
The limits are pedagogical rather than technical: this tool keeps the whole table in every recorded step, so the shape of the table sets the size of the trace directly, and a run has to stay short enough to sit and watch. An input that would take more than three thousand steps on this algorithm is refused before a single step is generated, from a formula in the input sizes rather than by running it and finding out.
An unfilled cell is drawn differently from a cell holding a zero — no fill, a dashed outline, and no number at all — because early in a run that difference is most of the picture.