AlgoFrames

0/1 and unbounded knapsack

Knapsack picks items to maximise value within a weight limit. A table row per item records whether taking or skipping each item is better.

Before you start: Kadane's algorithm and maximum subarray.

0/1 knapsack: take or skip each item

The idea

Items A, B and C weigh 1, 3 and 4 and are worth 15, 20 and 30. Which items should go into a bag that holds weight 4?

Intuition

Grabbing the most valuable item first picks C for 30 and fills the bag. A and B fit together and are worth 35.

A choice that looks best alone can block a better pair. To be sure, we compare every way to use each capacity, and a table does that without listing all subsets.

Each cell asks one question about its row's item. Skip it and keep the cell above, or take it and add its value to the cell w columns left.

dp[i][w] is the best value using the first i items with capacity w. Without item i the best is dp[i − 1][w]. With it, the rest of the bag holds w − wᵢ, so the best is dp[i − 1][w − wᵢ] + vᵢ.

Complexity

The table has (n + 1) × (W + 1) cells, each filled in O(1): O(n · W) time. Trying every subset costs 2ⁿ.

Each row reads only the row above, so one row of W + 1 values is enough. Sweep w from W down to 0: O(W) space.

Going right to left, dp[w − wᵢ] still holds the old row's value when dp[w] reads it. The item is then counted at most once.

Pitfalls

With one row, sweeping w upward reads values already updated for this item. Item A then counts four times.

O(n · W) grows with the number W, not with its digit count. A capacity of 10⁹ needs 10⁹ columns, far too many.

Running time that is polynomial in a number's value but exponential in its length is called pseudo-polynomial. Knapsack with huge weights is NP-hard.

Variations

Subset sum keeps true or false instead of a value: can some items hit sum s exactly? Partition asks for half the total.

Unbounded knapsack lets items repeat. The take arrow reads the same row, so an item can be taken again.

Unbounded knapsack: items that repeat

The idea

Now every item comes in unlimited copies, and the bag holds weight 6. Two copies of B fill it and are worth 80.

Intuition

The take arrow now stays in B's own row. dp[B][3] may already contain a B, so taking B again is allowed.

0/1 reads the row above, which has never seen item i, so i is used once. Reading the current row means the leftover space may itself hold more copies of i.

Here the best value per weight, B at 13.3, happens to win. Greedy by ratio still fails on other inputs, so the table stays.

Take items w3 v9 and w2 v5 with capacity 4. Ratio picks w3 first and leaves 1 unit empty: 9. Two copies of w2 give 10.

Complexity

The table is the same size as for 0/1: O(n · W) time. With one row and w running upward, space is O(W).

Pitfalls

With one row, unbounded sweeps w upward, the opposite of 0/1. dp[w − 3] already counts B, which is what we want here.

Best ratio first fails with copies too: A (ratio 3) fills 3 of the 4 units and leaves 1 empty, for 9. B + B gives 10.

Ratio greedy is right only when items can be cut into fractions. Whole items leave gaps, and a gap can cost more than the ratio gains.

Variations

Coin change is unbounded knapsack where each coin weighs its face value and is worth 1, and we minimise the count.

Rod cutting is the same table: piece lengths are weights, prices are values, and the rod length is the capacity.

Code

Pseudocode

knapsack(weights, values, W):
  n ← number of items
  dp ← (n + 1) × (W + 1) table of 0
  for i ← 1 to n
    wt ← weights[i - 1]; val ← values[i - 1]
    for w ← 0 to W
      dp[i][w] ← dp[i - 1][w]
      if wt ≤ w
        dp[i][w] ← max(dp[i][w], dp[i - 1][w - wt] + val)
  return dp[n][W]

Python

def knapsack(weights, values, capacity):
    n = len(weights)
    dp = [[0] * (capacity + 1) for _ in range(n + 1)]
    for i in range(1, n + 1):
        wt, val = weights[i - 1], values[i - 1]
        for w in range(capacity + 1):
            dp[i][w] = dp[i - 1][w]
            if wt <= w:
                dp[i][w] = max(dp[i][w], dp[i - 1][w - wt] + val)
    return dp[n][capacity]

JavaScript

function knapsack(weights, values, capacity) {
  const n = weights.length;
  const dp = Array.from({ length: n + 1 }, () => new Array(capacity + 1).fill(0));
  for (let i = 1; i <= n; i++) {
    const wt = weights[i - 1], val = values[i - 1];
    for (let w = 0; w <= capacity; w++) {
      dp[i][w] = dp[i - 1][w];
      if (wt <= w) dp[i][w] = Math.max(dp[i][w], dp[i - 1][w - wt] + val);
    }
  }
  return dp[n][capacity];
}

Java

static int knapsack(int[] weights, int[] values, int capacity) {
    int n = weights.length;
    int[][] dp = new int[n + 1][capacity + 1];
    for (int i = 1; i <= n; i++) {
        int wt = weights[i - 1], val = values[i - 1];
        for (int w = 0; w <= capacity; w++) {
            dp[i][w] = dp[i - 1][w];
            if (wt <= w) dp[i][w] = Math.max(dp[i][w], dp[i - 1][w - wt] + val);
        }
    }
    return dp[n][capacity];
}

Practice problems (7)

Fill the knapsack table Warm-up

Items A, B and C weigh 2, 3 and 4 and are worth 3, 4 and 6. The bag holds weight 5. Follow the 0/1 table and answer each question before the step plays.

Take or skip? Warm-up

Item C weighs 4 and is worth 30. The row above C holds 35 at capacity 4 and 0 at capacity 0; what does C's row hold at capacity 4?

0/1 knapsack Standard

Item i weighs weights[i] and is worth values[i]. A bag holds total weight at most capacity. Each item can go in once or not at all.

Return the largest total value that fits.

Partition equal subset sum Standard

Return true if nums can be split into two groups with equal sums, and false otherwise. Every number goes into exactly one group.

Unbounded knapsack Standard

Item i weighs weights[i] and is worth values[i]. You may take any number of copies of every item. The bag holds total weight at most capacity.

Return the largest total value that fits.

Spot the bug: one-row 0/1 knapsack Standard

This one-row version of 0/1 knapsack should use each item at most once, but it returns too much for some inputs. Click the line with the bug, then fix it.

Target sum Challenge

Put a + or a − in front of every number in nums, then add them all up. Return how many sign choices give exactly target.

Related topics

Next on the path: Coin change: minimum coins and number of ways