0/1 Knapsack visualization

Maximise value within a weight limit; each item is either taken once or left.

dp[i][c] = best value using the first i items with capacity c. For item i we either skip it (dp[i−1][c]) or take it if it fits (value + dp[i−1][c − weight]).

Edge cases: capacity 0 or no items gives 0; an item heavier than the capacity can never be taken; zero-weight items are always worth taking.

Complexity

Time: best O(n·W), average O(n·W), worst O(n·W). Space: O(n·W). Difficulty: Intermediate.

Pseudocode

procedure knapsack(w, v, W):
  dp[0][*] ← 0
  for i ← 1 to n:
    for c ← 0 to W:
      dp[i][c] ← dp[i−1][c]                 // skip item i
      if w[i] ≤ c:
        dp[i][c] ← max(dp[i][c], v[i] + dp[i−1][c−w[i]])
  trace back from dp[n][W] to list chosen items

More dynamic programming algorithms