← Back to Algorithms, page 5

algorithms-0081 · Medium mid

0/1 knapsack: choose items with given weights and values to maximise total value without exceeding a weight capacity, using each item at most once.

Let best[c] be the best value with capacity c using the items seen so far. For each item, update capacities from high to low: best[c] = max(best[c], best[c - w] + v). The downward order keeps each item from being used twice. Time O(n * cap), space O(cap); a 2D table is needed to recover which items were taken.

Full answer

Problem

Given n items with weights w[i] and values v[i] and a capacity W, return the maximum total value of a subset whose total weight is at most W.

Example: weights [1, 3, 4, 5], values [1, 4, 5, 7], W = 7 returns 9 (items of weight 3 and 4).

Constraints: n <= 100, W <= 10^4, weights and values positive integers.

Brute force

Try all 2^n subsets and keep the best feasible one: O(2^n * n).

Optimal approach

2D form: dp[i][c] = best value using the first i items with capacity c. Then dp[i][c] = dp[i-1][c] (skip) or dp[i-1][c - w] + v (take, if w <= c).

1D form: one array best[0..W]. For each item, loop c from W down to w and set best[c] = max(best[c], best[c - w] + v).

To recover the items, keep the 2D table and walk back from dp[n][W]: if dp[i][c] != dp[i-1][c], item i was taken, so subtract its weight.

Why it works

For the first i items and capacity c, an optimal choice either excludes item i (leaving the problem for i - 1 items and capacity c) or includes it (leaving i - 1 items and capacity c - w). Both are smaller subproblems, so the recurrence is complete. In the 1D form, iterating c downward means best[c - w] still holds the value from before item i was considered, which enforces "at most once". Iterating upward would turn it into the unbounded knapsack.

Complexity

O(n * W) time; O(W) space for the value only, O(n * W) to recover items. This is pseudo-polynomial; the decision version of knapsack is NP-complete, so no algorithm polynomial in the number of input bits is known.

Code

python
import random
from itertools import product


def knapsack(weights, values, cap):
    """0/1 knapsack: each item used at most once. 1D table iterated from high capacity down.
    O(n * cap) time, O(cap) space (pseudo-polynomial)."""
    best = [0] * (cap + 1)
    for w, v in zip(weights, values):
        for c in range(cap, w - 1, -1):  # downward so item i is not reused in the same pass
            best[c] = max(best[c], best[c - w] + v)
    return best[cap]


def knapsack_with_items(weights, values, cap):
    """2D table so the chosen items can be recovered."""
    n = len(weights)
    dp = [[0] * (cap + 1) for _ in range(n + 1)]
    for i in range(1, n + 1):
        w, v = weights[i - 1], values[i - 1]
        for c in range(cap + 1):
            dp[i][c] = dp[i - 1][c]
            if w <= c:
                dp[i][c] = max(dp[i][c], dp[i - 1][c - w] + v)
    chosen, c = [], cap
    for i in range(n, 0, -1):
        if dp[i][c] != dp[i - 1][c]:
            chosen.append(i - 1)
            c -= weights[i - 1]
    return dp[n][cap], chosen[::-1]


def brute(weights, values, cap):
    best = 0
    for pick in product((0, 1), repeat=len(weights)):
        if sum(w for w, p in zip(weights, pick) if p) <= cap:
            best = max(best, sum(v for v, p in zip(values, pick) if p))
    return best


if __name__ == "__main__":
    assert knapsack([1, 3, 4, 5], [1, 4, 5, 7], 7) == 9          # items of weight 3 and 4
    total, items = knapsack_with_items([1, 3, 4, 5], [1, 4, 5, 7], 7)
    assert total == 9 and sum([1, 3, 4, 5][i] for i in items) <= 7
    assert knapsack([], [], 10) == 0 and knapsack([5], [10], 4) == 0
    rng = random.Random(81)
    for _ in range(500):
        n = rng.randint(0, 9)
        ws = [rng.randint(1, 10) for _ in range(n)]
        vs = [rng.randint(0, 20) for _ in range(n)]
        cap = rng.randint(0, 30)
        t, its = knapsack_with_items(ws, vs, cap)
        assert knapsack(ws, vs, cap) == t == brute(ws, vs, cap) == sum(vs[i] for i in its)
    print("all tests passed")

Save as b81_knapsack.py and run python3 b81_knapsack.py. It prints all tests passed (Python 3.13.5).

Edge cases

No items or capacity 0 (value 0). Items heavier than the capacity (never taken). Zero-value items. Very large W with small n: switch to a DP over value (min weight for each value) or meet-in-the-middle over subsets.

Pattern

0/1 knapsack: a decision per item with a resource budget, iterating the budget downward in the 1D form. Same shape: partition equal subset sum, target sum with plus and minus signs, last stone weight II, and budgeted feature selection.

python
import random
from itertools import product


def knapsack(weights, values, cap):
    """0/1 knapsack: each item used at most once. 1D table iterated from high capacity down.
    O(n * cap) time, O(cap) space (pseudo-polynomial)."""
    best = [0] * (cap + 1)
    for w, v in zip(weights, values):
        for c in range(cap, w - 1, -1):  # downward so item i is not reused in the same pass
            best[c] = max(best[c], best[c - w] + v)
    return best[cap]


def knapsack_with_items(weights, values, cap):
    """2D table so the chosen items can be recovered."""
    n = len(weights)
    dp = [[0] * (cap + 1) for _ in range(n + 1)]
    for i in range(1, n + 1):
        w, v = weights[i - 1], values[i - 1]
        for c in range(cap + 1):
            dp[i][c] = dp[i - 1][c]
            if w <= c:
                dp[i][c] = max(dp[i][c], dp[i - 1][c - w] + v)
    chosen, c = [], cap
    for i in range(n, 0, -1):
        if dp[i][c] != dp[i - 1][c]:
            chosen.append(i - 1)
            c -= weights[i - 1]
    return dp[n][cap], chosen[::-1]


def brute(weights, values, cap):
    best = 0
    for pick in product((0, 1), repeat=len(weights)):
        if sum(w for w, p in zip(weights, pick) if p) <= cap:
            best = max(best, sum(v for v, p in zip(values, pick) if p))
    return best


if __name__ == "__main__":
    assert knapsack([1, 3, 4, 5], [1, 4, 5, 7], 7) == 9          # items of weight 3 and 4
    total, items = knapsack_with_items([1, 3, 4, 5], [1, 4, 5, 7], 7)
    assert total == 9 and sum([1, 3, 4, 5][i] for i in items) <= 7
    assert knapsack([], [], 10) == 0 and knapsack([5], [10], 4) == 0
    rng = random.Random(81)
    for _ in range(500):
        n = rng.randint(0, 9)
        ws = [rng.randint(1, 10) for _ in range(n)]
        vs = [rng.randint(0, 20) for _ in range(n)]
        cap = rng.randint(0, 30)
        t, its = knapsack_with_items(ws, vs, cap)
        assert knapsack(ws, vs, cap) == t == brute(ws, vs, cap) == sum(vs[i] for i in its)
    print("all tests passed")

1D downward table, 2D table with item recovery, and an exhaustive subset check on random instances.

Complexity

Time: O(n * W). Space: O(W) value only; O(n * W) with item recovery. Pseudo-polynomial; for huge W and small n, use DP over value or meet-in-the-middle.

By level

Fresher: Writes the 2D table with take or skip and fills it on a small example. Explains why greedy by ratio does not work for 0/1 items.

Mid: Compresses to 1D with the downward loop and explains why the direction matters. Recovers chosen items from the 2D table.

Senior: Discusses pseudo-polynomial time and NP-completeness, DP over value, meet-in-the-middle, and approximation schemes. Applies multi-constraint knapsack thinking to resource allocation.

Key points

  • Take or skip each item once
  • 1D loop runs capacity downward
  • Upward loop gives unbounded knapsack
  • Recover items from the 2D table
  • Pseudo-polynomial O(n * W)

Common mistakes

  • Iterating capacity upward in the 1D version
  • Sorting by value-to-weight ratio greedily (that is only correct for fractional knapsack)
  • Losing the item list after compressing to 1D
  • Calling O(n * W) polynomial without qualification

Follow-ups

  • How do you solve it if W is 10^9 but n is 40?
  • How does fractional knapsack differ?
  • How would you handle a second constraint such as volume?

Tips

  • State the take-or-skip recurrence before coding
  • Explain the downward loop
  • Mention pseudo-polynomial time

Evaluation rubric

  • Correct recurrence
  • Correct loop direction
  • Item recovery
  • Correct complexity discussion