10. Knapsack Problem

Pack the most value into a fixed-capacity bag

You're a burglar with a bag that holds at most 7 kg. In front of you are four items, each with a weight and a value. You can take each item or leave it — no cutting items in half. Which combination of items maximizes the total value without exceeding the weight limit?

This is the 0/1 knapsack problem, one of the most studied problems in computer science and operations research. It's the canonical example of a problem where greedy intuition fails and dynamic programming saves the day.

The Problem Statement

Given n items, each with a weight w[i] and a value v[i], and a knapsack with capacity W, find the subset of items that maximizes the total value while keeping total weight ≤ W.

Two Flavors of Knapsack

0/1 Knapsack: Each item is either taken whole or left behind. No partial items allowed. This is the hard version — it requires dynamic programming.

Fractional Knapsack: You can take fractions of items (e.g., half a gold bar). This version is easy — a simple greedy algorithm solves it optimally.

A Simple Example

4 items, capacity W = 7

Item    Weight    Value    Value/Weight
  A       1         1        1.00
  B       3         4        1.33
  C       4         5        1.25
  D       5         7        1.40

If we pick by best value/weight ratio (greedy), we'd take D (weight 5, value 7), then A (weight 1, value 1). Total: weight 6, value 8.

But the optimal solution is B + C: weight 3 + 4 = 7, value 4 + 5 = 9. Greedy missed it!

The greedy approach failed because taking the "best" single item blocked a more valuable combination. To find the true optimum, we need to consider all possible subsets — or be smarter about it with dynamic programming.

The Recursive Insight

For each item, there are exactly two choices: include it or exclude it. This gives us a clean recursive structure:

The Core Recurrence

For item i with remaining capacity w:

  • If w[i] > w (item too heavy): skip it. knapsack(i-1, w)
  • Otherwise: take the better of:
    • Skip: knapsack(i-1, w)
    • Take: v[i] + knapsack(i-1, w - w[i])

Pseudocode (Recursive)

function knapsack(items, i, w):
    if i == 0 or w == 0:
        return 0

    if items[i].weight > w:
        return knapsack(items, i-1, w)    // can't take it

    return max(
        knapsack(items, i-1, w),                           // skip item i
        items[i].value + knapsack(items, i-1, w - items[i].weight)  // take item i
    )

This works, but the recursion tree branches at every item, leading to O(2n) time. Many subproblems are solved repeatedly — the classic signal that dynamic programming will help.

The Dynamic Programming Table

Build an (n+1) x (W+1) table where dp[i][w] holds the maximum value achievable using items 1..i with capacity w.

  1. Initialize the borders

    Row 0 (no items): all zeros — you can't get any value with no items.
    Column 0 (zero capacity): all zeros — you can't carry anything.

  2. Fill left-to-right, top-to-bottom

    For each cell dp[i][w]:
    If weight[i] > w: dp[i][w] = dp[i-1][w] (can't fit, skip).
    Otherwise: dp[i][w] = max(dp[i-1][w], value[i] + dp[i-1][w - weight[i]]).

  3. Read the answer

    The bottom-right cell dp[n][W] is the maximum value.

Worked Example: 4 Items, Capacity 7

The completed DP table

Items: A(w=1,v=1)  B(w=3,v=4)  C(w=4,v=5)  D(w=5,v=7)

    w=  0   1   2   3   4   5   6   7
none    0   0   0   0   0   0   0   0
   A    0   1   1   1   1   1   1   1
   B    0   1   1   4   5   5   5   5
   C    0   1   1   4   5   6   6   9
   D    0   1   1   4   5   7   8   9</code></pre>

The bottom-right cell is 9, confirming the optimal value.

Let's trace how key cells were filled:

Cell dp[2][3]: items {A,B}, capacity 3

Item B has weight 3 ≤ 3, so we can take it.
dp[2][3] = max(
    dp[1][3],              // skip B: 1
    4 + dp[1][3 - 3]       // take B: 4 + dp[1][0] = 4 + 0 = 4
) = max(1, 4) = 4

Cell dp[3][7]: items {A,B,C}, capacity 7

Item C has weight 4 ≤ 7, so we can take it.
dp[3][7] = max(
    dp[2][7],              // skip C: 5
    5 + dp[2][7 - 4]       // take C: 5 + dp[2][3] = 5 + 4 = 9
) = max(5, 9) = 9

Cell dp[4][7]: items {A,B,C,D}, capacity 7

Item D has weight 5 ≤ 7, so we can take it.
dp[4][7] = max(
    dp[3][7],              // skip D: 9
    7 + dp[3][7 - 5]       // take D: 7 + dp[3][2] = 7 + 1 = 8
) = max(9, 8) = 9

Backtracking: Which Items Were Selected?

The DP table tells you the maximum value, but not which items to pack. To recover the selection, trace backward from dp[n][W]:

Backtracking through the table

Start at dp[4][7] = 9
  dp[4][7] == dp[3][7]?  9 == 9 → yes → skip D, move to dp[3][7]
  dp[3][7] == dp[2][7]?  9 == 5 → no  → TAKE C, move to dp[2][7-4] = dp[2][3]
  dp[2][3] == dp[1][3]?  4 == 1 → no  → TAKE B, move to dp[1][3-3] = dp[1][0]
  dp[1][0] == 0 → done

Selected items: B (w=3, v=4) + C (w=4, v=5) Total weight: 7, Total value: 9

The Complete Algorithm

function knapsack(weights, values, n, W):
    // Create (n+1) × (W+1) table
    dp = new array[n+1][W+1], initialized to 0

    // Fill the table
    for i from 1 to n:
        for w from 1 to W:
            if weights[i] > w:
                dp[i][w] = dp[i-1][w]
            else:
                dp[i][w] = max(
                    dp[i-1][w],
                    values[i] + dp[i-1][w - weights[i]]
                )

    // Backtrack to find selected items
    selected = []
    w = W
    for i from n down to 1:
        if dp[i][w] != dp[i-1][w]:
            selected.add(item i)
            w = w - weights[i]

    return dp[n][W], selected

The Fractional Knapsack (Greedy Approach)

When you can take fractions of items, the problem becomes much simpler. Sort items by value-per-unit-weight in descending order, then greedily take as much of each item as possible:

function fractionalKnapsack(items, W):
    sort items by (value / weight) descending
    totalValue = 0
    remaining = W

    for each item in items:
        if item.weight ≤ remaining:
            take all of it
            totalValue += item.value
            remaining -= item.weight
        else:
            take fraction = remaining / item.weight
            totalValue += item.value * fraction
            remaining = 0
            break

    return totalValue

Fractional knapsack with our 4 items, W = 7

Sorted by value/weight: D(1.40), B(1.33), C(1.25), A(1.00)

Take all of D: weight 5, value 7.00 (remaining: 2) Take 2/3 of B: weight 2, value 2.67 (remaining: 0)

Total value: 9.67

The fractional solution (9.67) is better than the 0/1 solution (9) because it can take partial items. But this approach requires being able to split items.

Why Greedy Fails for 0/1 Knapsack

Counterexample

Item    Weight    Value    Value/Weight
  X       6        10       1.67
  Y       4         7       1.75
  Z       4         7       1.75

Capacity W = 8

Greedy (by ratio): Take Y (w=4, v=7), then Z (w=4, v=7) Total: weight 8, value 14 ← happens to work here

But consider: X 10 10 1.00 Y 5 6 1.20 Z 5 6 1.20

Capacity W = 10

Greedy (by ratio): Take Y (w=5, v=6), then Z (w=5, v=6) Total: weight 10, value 12

Optimal: Take X alone → weight 10, value 10? No... Actually: Y + Z = 12 > 10. Greedy wins here.

Better counterexample: X 3 4 1.33 Y 4 5 1.25 Z 5 7 1.40

Capacity W = 7

Greedy (by ratio): Take Z (w=5, v=7), then X (w=3 > 2 remaining) skip, done. Total: weight 5, value 7

Optimal: X + Y → weight 7, value 9

The greedy approach picks the single item with the best ratio, but that can block better combinations. The 0/1 constraint means you cannot compensate by taking a fraction of another item.

Complexity: Pseudo-Polynomial Time

Time and Space

Time: O(nW) — we fill every cell in the n x W table exactly once.
Space: O(nW) for the full table, or O(W) if you only keep two rows at a time (though you lose the ability to backtrack).

O(nW) looks polynomial, but there's a subtlety: W is a number, not a count of input elements. The size of the input for W is log W bits. So O(nW) is actually exponential in the number of bits needed to represent W.

Why "pseudo-polynomial" matters

If W = 100 and n = 10:
  Table has 1,000 cells — very fast.

If W = 1,000,000 and n = 10: Table has 10,000,000 cells — still manageable.

If W = 10^18 and n = 10: Table has 10^19 cells — impossible.

The input "10^18" is only 60 bits long, but the algorithm does 10^19 operations. That's exponential in input length.

Algorithms whose runtime depends on the numeric value of the input rather than its size are called pseudo-polynomial. They're fast when numbers are small, but not truly polynomial.

NP-Completeness

The 0/1 knapsack problem is NP-complete (more precisely, the decision version — "is there a subset with value ≥ V and weight ≤ W?" — is NP-complete). This means:

Property What it means
NP Given a proposed solution, you can verify it in polynomial time
NP-hard At least as hard as every other problem in NP
NP-complete Both NP and NP-hard — the "hardest" problems in NP

No one has found a polynomial-time algorithm for knapsack (and most researchers believe none exists — this is the famous P vs NP question). In practice, the pseudo-polynomial DP solution works well when W is reasonable, and there are good approximation algorithms for when it's not.

Where the Knapsack Problem Appears

Application How it maps to knapsack
Resource allocation Allocate a fixed budget across projects to maximize return
Budget optimization Choose which features to build within a limited development budget
Cargo loading Pack a truck or container with goods to maximize shipped value
Cutting stock Cut raw material into pieces with minimum waste
Portfolio selection Choose investments to maximize expected return within a risk budget
Cryptography Subset-sum (a knapsack variant) is the basis for some cryptographic schemes

Key Takeaways

  • The 0/1 knapsack problem asks: which items maximize value without exceeding a weight limit?
  • For each item, the choice is binary — take it or leave it — giving a clean recursive structure
  • Dynamic programming builds an n x W table, solving each subproblem exactly once
  • Backtracking through the table recovers which items were selected
  • The fractional knapsack is solvable greedily (sort by value/weight ratio), but greedy fails for 0/1
  • The O(nW) runtime is pseudo-polynomial — fast when W is small, but exponential in the bit-length of W
  • The knapsack problem is NP-complete, one of the foundational hard problems in computer science
  • It appears everywhere: budgets, cargo, portfolios, cutting stock, and even cryptography

The knapsack problem is a perfect illustration of why dynamic programming exists. The brute-force approach considers 2n subsets, but DP collapses all that redundancy into an elegant table. It's also a gateway to understanding computational complexity — the surprising fact that some problems with simple descriptions have no known efficient solution.