Skip to main content
Advanced ~15 min read

0/1 Knapsack

Where greedy fails and DP shines: pick items under a weight budget to maximize value, the template for a whole family of problems.

Prerequisites: Dynamic Programming, Greedy Algorithms

You have n items, each with a weight and a value, and a knapsack that holds at most W weight. Each item goes in whole or not at all (that's the "0/1"). Maximize total value without exceeding W. It sounds like a packing puzzle, but it is the abstract shape of budget allocation, portfolio selection under capital limits, cutting stock, and cloud-resource packing.

The greedy reflex, grab the most valuable items, or the best value-per-kilo, fails. Items interact through the budget: a heavy item that is great per-kilo can strand capacity that two moderate items would have used better. Dynamic programming handles the interaction by making the state explicit: dp[i][w] = the best value using only the first i items with capacity w remaining. Item i forces one honest decision, leave it (dp[i-1][w]) or take it (value[i] + dp[i-1][w - weight[i]], only when it fits). The answer is the better branch. Every cell, every item, every capacity level, no regrets, no greed.

The 2-D table, then the space trick

knapsack.js
function knapsack(values, weights, W) {
  const n = values.length;
  // dp[i][w]: best value using first i items within capacity w
  const dp = Array.from({ length: n + 1 }, () => new Array(W + 1).fill(0));

  for (let i = 1; i <= n; i++) {
    for (let w = 0; w <= W; w++) {
      dp[i][w] = dp[i - 1][w];                        // skip item i
      if (weights[i - 1] <= w) {                      // item fits…
        dp[i][w] = Math.max(
          dp[i][w],
          values[i - 1] + dp[i - 1][w - weights[i - 1]], // …or take it
        );
      }
    }
  }
  return dp[n][W];
}

// Space-optimized: one row, iterated RIGHT-TO-LEFT so each item is used once
function knapsack1D(values, weights, W) {
  const dp = new Array(W + 1).fill(0);
  for (let i = 0; i < values.length; i++) {
    for (let w = W; w >= weights[i]; w--) {           // backwards = 0/1 semantics
      dp[w] = Math.max(dp[w], values[i] + dp[w - weights[i]]);
    }
  }
  return dp[W];
}

Cost summary

Operation / caseCostNotes
TimeO(n·W)every item × every capacity level
Space-optimizedO(n·W)reverse inner loop preserves 0/1 semantics
Recover chosen itemsO(n + W)walk the 2-D table backwards, re-deriving each take/leave decision

O(n·W) is pseudo-polynomial: exponential in the bit-length of W. Knapsack is NP-hard in general, the DP is fast only when W is reasonably small. Saying this sentence in an interview is worth points.

Practice

Items: (value 60, weight 50), (value 40, weight 25), (value 40, weight 25). Capacity W = 50. What is the maximum total value?

Reveal explanation

25 + 25 = 50 ≤ W, value 40 + 40 = 80 > 60. The DP considers taking both small items at capacity level 50, greedy value-first never does.

Check your understanding

  1. 1.Why does the space-optimized version loop w from W down to weights[i]?
  2. 2.dp[i][w] = max(dp[i-1][w], values[i-1] + dp[i-1][w - weights[i-1]]). What do the two branches represent?
  3. 3.Subset-sum: does any subset of [3, 34, 4, 12, 5, 2] sum to 9? This is knapsack with:

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Keep going