Subroutine Logo
Subroutine
← Back to Playground Algorithms Intermediate

Dynamic Programming: The 0/1 Knapsack Problem

Understand sub-problem optimization, memoization matrices, and pseudo-polynomial time complexity.

Published: 2026-07-26
#Algorithms#Dynamic Programming#Knapsack#Optimization

The 0/1 Knapsack Problem is a classic combinatorial optimization problem. Given NN items, each with a specific weight wiw_i and value viv_i, and a knapsack with maximum weight capacity WW, determine the maximum total value of items that can fit in the knapsack.

Unlike the fractional knapsack problem (which can be solved greedily), 0/1 Knapsack requires Dynamic Programming (DP) because items cannot be broken into fractions.


1. Summary & Key Takeaways

  • Sub-Problem Recurrence Relation: DP[i][w]=max(DP[i1][w],vi+DP[i1][wwi])DP[i][w] = \max\left(DP[i-1][w], \, v_i + DP[i-1][w - w_i]\right)
  • State Definition: DP[i][w]DP[i][w] represents the maximum value achievable considering the first ii items with capacity ww.
  • Time Complexity: O(NW)O(N \cdot W) pseudo-polynomial time (where NN is item count and WW is capacity).
  • Space Complexity: O(NW)O(N \cdot W) using a full 2D table, or O(W)O(W) space using 1D space optimization.

2. Interactive Knapsack Playground

Use the interactive memoization matrix below to step through sub-problem evaluations cell-by-cell!

Dynamic Programming Recurrence

Click Step 1 DP Cell to watch the matrix evaluate whether including the current item yields higher total value than excluding it!

0/1 Knapsack Dynamic ProgrammingMemoization Matrix

Fill the 2D DP matrix DP[i][w] = max(DP[i-1][w], val[i] + DP[i-1][w-wt[i]]) cell-by-cell!

Max Value: $0
Evaluating Gemstone (Weight: 2, Value: $3) at Capacity W=0wt > W (2 > 0): Exclude item -> Copy DP[0][0] = $0
Gemstone
Wt: 2$3
Gold Bar
Wt: 3$4
Artifact
Wt: 4$5
Crown
Wt: 5$8
Item \ WtW=0W=1W=2W=3W=4W=5W=6W=7
No Items00000000
Gemstone00000000
Gold Bar00000000
Artifact00000000
Crown00000000
Knapsack Dynamic Programming Code
knapsack_dp.py
Python
# 0/1 Knapsack Dynamic Programming in Python

def knapsack(W, weights, values):
    n = len(values)
    dp = [[0] * (W + 1) for _ in range(n + 1)]

    for i in range(1, n + 1):
        for w in range(W + 1):
            if weights[i - 1] <= w:
                dp[i][w] = max(dp[i - 1][w], values[i - 1] + dp[i - 1][w - weights[i - 1]])
            else:
                dp[i][w] = dp[i - 1][w]

    return dp[n][W]

3. Formulated Memoization Matrix Solution

For the sample catalog below (W=7W = 7):

  • Gemstone: Weight =2= 2, Value =\3$
  • Gold Bar: Weight =3= 3, Value =\4$
  • Artifact: Weight =4= 4, Value =\5$
  • Crown: Weight =5= 5, Value =\8$

Here is the completed DP[i][w]DP[i][w] state matrix:

Item \ WtW=0W=1W=2W=3W=4W=5W=6W=7
No Items0000000000000000
Gemstone0000\3$\3$\3$\3$\3$\3$
Gold Bar0000\3$\4$\4$\7$\7$\7$
Artifact0000\3$\4$\5$\7$\8$\9$
Crown0000\3$\4$\5$\8$\8$\11$

At capacity W=7W=7, the optimal combination takes the Crown (W=5, V=\8)+Gemstone() + **Gemstone** (W=2, V=$3)foramaximumprofitof) for a maximum profit of **$11$**!


4. Knapsack Variants Matrix

VariantFractional Split Allowed?Optimal StrategyTime Complexity
0/1 Knapsack❌ No (Take item whole or leave)Dynamic ProgrammingO(NW)O(N \cdot W)
Fractional Knapsack✅ Yes (Take fractions of items)Greedy Algorithm (Value/Weight ratio)O(NlogN)O(N \log N)
Unbounded Knapsack❌ No (Unlimited duplicate items)Dynamic Programming (1D array)O(NW)O(N \cdot W)