Algorithms · Visualized

DP: 0/1 Knapsack

Dynamic Programming

Break problems into overlapping subproblems and store answers.

Given items with weights and values, and a knapsack with a weight capacity, maximize total value by choosing a subset of items (each item either fully taken or left behind — no fractions, unlike Fractional Knapsack). Time: O(n × capacity) average, O(n × capacity) worst; space: O(n × capacity), reducible to O(capacity) with a 1D rolling array.

Big-O: The most-asked interview category — 35 classics here.

0/1 Knapsack

Dynamic Programming

Given items with weights and values, and a knapsack with a weight capacity, maximize total value by choosing a subset of items (each item either fully taken or left behind — no fractions, unlike Fractional Knapsack). dp[i][w] represents the best value achievable using the first i items within weight capacity w.

How 0/1 Knapsack Works

  1. Create a DP table where dp[i][w] represents the maximum value achievable using the first i items with a weight limit of w. Initialize dp[0][w] = 0 for all w (no items means no value).
  2. For each item i and each possible weight capacity w, decide: don't include item i (value stays dp[i-1][w]), or include item i if it fits (value becomes item's value + dp[i-1][w - item's weight]).
  3. Set dp[i][w] to the maximum of these two options (only consider including the item if its weight doesn't exceed w).
  4. Fill the table for every item and every weight capacity up to the knapsack's total capacity.
  5. Return dp[n][capacity] (n = total number of items) as the maximum achievable value.

0/1 Knapsack Worked Example

Input: {items: [{weight: 1, value: 1}, {weight: 3, value: 4}, {weight: 4, value: 5}, {weight: 5, value: 7}], capacity: 7}

Building the table across items and weight capacities: considering item1(w1,v1), item2(w3,v4), item3(w4,v5), item4(w5,v7). The best combination within capacity7 turns out to be item2+item3 (weight 3+4=7, value 4+5=9), giving a maximum value of 9.

DP: 0/1 KnapsackO(n·W)
Max value within a weight capacity.
1
0
3
1
4
2
5
3
01234567
none00000000
item 100000000
item 200000000
item 300000000
item 400000000
capacity7
Step 1 / 34
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
0/1 Knapsack: dp[i][w] = max value using items 1..i with capacity w.
Python · Dynamic Programming Algorithms in Code
def knapsack(weights, values, capacity):
    n = len(weights)
    dp = [[0] * (capacity + 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(capacity + 1):
            dp[i][c] = dp[i - 1][c]
            if w <= c:
                dp[i][c] = max(dp[i][c], dp[i - 1][c - w] + v)
    return dp[n][capacity]

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

0/1 Knapsack Time & Space Complexity

BestO(n × capacity)
AverageO(n × capacity)
WorstO(n × capacity)
SpaceO(n × capacity), reducible to O(capacity) with a 1D rolling array

When to Use 0/1 Knapsack

  • Resource allocation with binary choices: selecting a subset of projects, cargo items, or investments to maximize value within a fixed budget/capacity.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.