Visualizers
0/1 Knapsack Visualizer
Solve the 0/1 Knapsack problem step-by-step using a 2D matrix.
native
Client-side
Ready to compute.
Execution Log
Max Value: -
Selected Items: -
Current Action:
Idle
Legend:
Uncomputed
Active Lookups
Calculated Max Value
Backtrack Path
0/1 Knapsack Algorithm
The 0/1 Knapsack problem is a classic combinatorial optimization problem. Given weights and values of $n$ items, put them in a knapsack of capacity $W$ to get the maximum total value. "0/1" means items are indivisible (you either take an item or leave it).
Dynamic Programming Formula
We maintain a 2D table `dp[i][w]` which stores the max value using a subset of first $i$ items with capacity $w$:
- If weight of item $i > w$: `dp[i][w] = dp[i-1][w]`
- Else: `dp[i][w] = max(dp[i-1][w], dp[i-1][w - wt[i-1]] + val[i-1])`
Implementation
function knapsack(W, weights, values) {
const n = weights.length;
const dp = Array.from({ length: n + 1 }, () => Array(W + 1).fill(0));
for (let i = 1; i <= n; i++) {
const wt = weights[i - 1];
const val = values[i - 1];
for (let w = 1; w <= W; w++) {
if (wt > w) {
dp[i][w] = dp[i - 1][w];
} else {
dp[i][w] = Math.max(dp[i - 1][w], dp[i - 1][w - wt] + val);
}
}
}
return dp[n][W];
}