0/1 and unbounded knapsack

Video lessonComing soon

1 A bag with a weight limit

We are packing a bag that holds 6 kg. Three things could go in. Each has a weight and a value, in thousands of rupees:

itemweightvaluevalue per kg
A231.5
B341.33
C451.25

Each thing goes in whole or stays out. We want the most value that fits. This is the 0/1 knapsack: 0 for out, 1 for in.

The greedy lesson tried the obvious rule on a bag like this: best value per kg first. Here it takes A, then B. That is 5 kg, worth 7, and C does not fit in the last 1 kg. But A and C together weigh 6 kg and are worth 8. B used up room that C needed, and greedy never goes back.

So we have to try the choices. The pick-or-skip lesson tried every subset with a tree, about 2ⁿ of them. With 100 items, that is far too many. This lesson fills a table instead, with one row per item and one column per kg of room.

2 The state: items and room

Two numbers say how much of the problem is left: how many items we may still use, and how much room the bag has. They are the state.

best[i][c] is the most value from the first i items in a bag that holds c kg. The answer for our bag is best[3][6].

To work out best[i][c], we look at the last of those items, item i − 1. It gives the take-or-skip choice from the robber's street:

  • Skip it. The room stays c, and the first i − 1 items fill it: best[i - 1][c].
  • Take it. It uses wt[i - 1] kg and adds val[i - 1]. The first i − 1 items fill the rest of the room: best[i - 1][c - wt[i - 1]] + val[i - 1]. This needs wt[i - 1] ≤ c.
best[i][c] = max(best[i − 1][c], best[i − 1][c − wt] + val)

Row 0 has no items, so every cell in it is 0. That is the base case.

On the table, each cell reads two cells in the row above. The skip is straight above it. The take is wt columns to the left of that:

c0123456–0000000ABC
best[3][6] (blue) reads two cells (orange). C weighs 4

Both reads are in the row above. Once item i − 1 is in the bag, only the items before it are left, so it cannot go in twice. The unbounded version changes exactly this.

3 Filling the table row by row

Each row needs only the row above it, so we fill the rows from top to bottom:

Filling best, one item at a time
c0123456–0000000ABC
Row –: no items, so every cell is 0

Here is row C in detail. C weighs 4 and is worth 5, so skip is best[2][c] and take is best[2][c - 4] + 5:

cskiptakebest[3][c]
00no room0
10no room0
23no room3
34no room4
440 + 5 = 55
570 + 5 = 57
673 + 5 = 88

At c = 5, taking C leaves 1 kg, and nothing fits in it, so skipping wins with A and B. At c = 6, taking C leaves 2 kg, and A fits there. That beats A and B by 1.

4 Which items went in

The table holds the choices too. We start at the answer, best[3][6], and compare each cell with the one straight above it:

  • They are equal. Skipping this row's item gave the same value, so it stayed out. Move up a row.
  • The cell is bigger. The item went in. Move up a row, and take its weight off c.
Walking back from best[3][6]
c0123456–0000000A0033333B0034477C0034578
8 is more than 7: C went in. c = 6 − 4 = 2
ABC
blue: in the bag

The bag holds A and C: 6 kg, worth 8. In pseudocode:

c = capacity
for i from n down to 1:
    if best[i][c] != best[i - 1][c]:
        item i - 1 went in
        c = c - wt[i - 1]

5 One row, filled right to left

Row i reads only row i − 1, so the space lesson's idea applies: keep one row and write each new row over it. The order inside the row now matters.

When we write best[c], we read best[c] and best[c - wt]. The second sits to the left. It must still hold the old row, the one without this item. Here is item A, weight 2, value 3, going into a row of zeros both ways:

Item A into one row, both ways
00013203040506c
Left to right, c = 2: 0 + 3 = 3

Left to right, best[2] already counts A when best[4] reads it, so A goes in twice. By c = 6 it is in three times, and the row ends [0, 0, 3, 3, 6, 6, 9]. Right to left, every cell to the left of c is still untouched in this pass, so it holds the row above. That is the 2-D formula, cell for cell.

The inner loop stops at wt[i], so c - wt[i] never goes below 0. Every tab returns 8 for our bag.

C++

When values get large, use long long. An int holds about 2 × 10⁹. If the total value can pass that, make best a vector<long long>.

When values get large, use long. An int holds about 2 × 10⁹. If the total value can pass that, make best a long[].

The - 1 in the range. range(capacity, wt[i] - 1, -1) counts down and stops before its end, so its last value is wt[i].

Numbers are safe here. They stay exact up to about 9 × 10¹⁵.

An if instead of max. Older versions of Go have no built-in max for integers, so the code compares take with best[c] itself. int is 64 bits, so large totals fit.

Indexes are usize. The capacity and each weight become usize once. (weight..=capacity).rev() counts down, and it is empty when the item is heavier than the bag.

When values get large, use long. An int holds about 2 × 10⁹. If the total value can pass that, make best a long[].

The cost follows from the two loops. They visit each item once and each capacity up to W, so time is O(n·W). The one row takes O(W) space, where the full table took O(n·W). With 100 items and W = 10⁵, that is 10⁷ steps, well inside the time limit. With W = 10⁹ it is 10¹¹ steps, and it gets TLE. The cost grows with the value of W, not with how many digits it has. This is called pseudo-polynomial.

6 Unbounded: the same loop, left to right

In the unbounded knapsack, each item can go in as many times as we like. The left-to-right loop above put A in twice. For 0/1 that was a bug. Here it is exactly what we want.

0/1:        c from capacity down to wt[i]
unbounded:  c from wt[i] up to capacity

That one line is the whole difference. The update inside the loop stays the same. Left to right, best[c - wt[i]] has already seen this item. It may hold one copy of it, or several, so adding one more copy is allowed. On our bag, the unbounded answer is 9: A three times, 6 kg.

Two roadmap problems are this loop in disguise:

  • Coin Change. It asks for the fewest coins that make an amount exactly. Coins are items that repeat, the amount is the capacity, and each coin adds 1. Each cell keeps the smaller of best[c] and best[c - coin] + 1. best[0] starts at 0, and every other cell starts at infinity, which means "cannot be made yet".
  • Rod cutting. A rod of length L sells in pieces, and a piece of length k sells for price[k]. Each length is an item with weight k and value price[k], and L is the capacity.

7 Yes or no, and how many ways

The same loop answers other questions. Only what a cell holds, its start and how two values combine change. Each number is used once here, so c runs high to low:

problembest[c] holdsstart
Subset sumcan we make c?true at 0 only
Count subsetsways to make c1 at 0, else 0

For a number x, subset sum sets best[c] to best[c] or best[c - x]. Counting adds: best[c] += best[c - x].

Partition Equal Subset Sum is subset sum with c = half the total. Target Sum and Count Partitions with a Given Difference turn into a count of subsets once we work out the sum one side must reach.

Counting ways with coins (Coin Change II) is unbounded, so c runs low to high. Here the nesting of the two loops matters too. With coins [1, 2] and amount 3:

// coins outside: ways[3] = 2
for coin in coins:
    for c from coin up to amount:
        ways[c] += ways[c - coin]

// amount outside: ways[3] = 3
for c from 1 up to amount:
    for coin in coins:
        if coin <= c:
            ways[c] += ways[c - coin]

With coins outside, we get 1+1+1 and 1+2. All the 1s go in before any 2. Each mix of coins comes out in one fixed order, so it counts once. These are combinations, what Coin Change II asks for. With the amount outside, every cell tries every coin as the last one, so 1+2 and 2+1 count as two, and 1+1+1 makes three. These are permutations.

8 Mistakes and edge cases

  • Wrong direction. Left to right in a 0/1 problem uses an item more than once. Our bag returns 9 instead of 8.
  • Wrong nesting when counting ways. With the amount loop outside, coins [1, 2] and amount 3 give 3 instead of 2.
  • Wrong start for "exactly". When the bag must be exactly full, every cell but best[0] starts at minus infinity. With zeros, best[1] on our bag says 0, though nothing weighs 1 kg. In Coin Change, coins [2] and amount 3 should return −1, but zeros give 0.
  • Infinity that overflows. If infinity is the largest int, best[c - coin] + 1 goes past it. In Coin Change, amount + 1 works as infinity, because no answer uses more coins than the amount.
  • Counts that overflow. n numbers have 2ⁿ subsets. With 100 numbers, the count passes any 64-bit type. Take the modulo the problem gives, such as 10⁹ + 7, after every addition.

9 When to use it

The sign is a set of items to pick from, and a target sum or a capacity to fill or reach. Then ask two questions:

  • Can an item be used more than once? No: 0/1, c runs high to low. Yes: unbounded, c runs low to high.
  • What does the problem want? The most or the least value takes max or min, "is it possible" takes or, and "how many ways" takes a sum.

The capacity becomes the length of the row, so it must be small enough to index: up to about 10⁴ or 10⁵. When the sums reach 10⁹ but there are only a few dozen items, this table is the wrong tool, and the items need another approach, such as splitting them into two halves.

The next lesson, on DP over two strings, fills a 2-D table again. This time both indexes walk along a string.

Before writing a knapsack loop, say out loud whether an item can repeat. That one answer picks the direction of the loop over c.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.