0/1 Knapsack Problem
A combinatorial optimization problem: Given a set of items, each with a weight and a value, determine which items to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible.
0/1 Knapsack Problem
A combinatorial optimization problem: Given a set of items, each with a weight and a value, determine which items to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible.
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | |
|---|---|---|---|---|---|---|---|---|
| Base | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| I1(w:1,v:1) | 0 | 0 1,1 | 0 | 0 | 0 | 0 | 0 | 0 |
| I2(w:3,v:4) | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| I3(w:4,v:5) | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| I4(w:5,v:7) | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
Checking Item 1 (Wt: 1, Val: 1) for Capacity 1
Fill the knapsack table
Order the steps of the 0/1 knapsack DP.
Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.
- 1Drop a step here
- 2Drop a step here
- 3Drop a step here
- 4Drop a step here
- 5Drop a step here
Test your knowledge
What does dp[i][w] represent?
The short version
Think of a thief robbing a store with a small backpack. He can't take everything. He must choose a combination of items that fits in the bag but has the highest total resale value.
In more depth
The Choice Diagram
The Knapsack problem represents the classic Constraint Optimization pattern. For every item, you have a choice:
We take the maximum of these two choices.
0/1 vs Unbounded:
When to reach for this
- Maximize value given a capacity constraint
- Find if a subset sums to a Detailed Target
- Min/Max number of ways to reach a target using elements
Interview Questions
Love this visualization?
Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.
100% free • No credit card required