Loading algorithms…

Loading visualizer…

Algorithms/Dynamic Programming/0/1 Knapsack

0/1 Knapsack Problem

Dynamic ProgrammingHard

Maximize total value under weight capacity limit using bottom-up DP table & traceback

SPEED
DP TABLE GRID: dp[items][capacity]
Active
Skip (dp[i-1][w])
Include
Selected

KNAPSACK CONTAINER (0 items selected)

Total Value: 0
Weight Capacity0 / 7
No items selected yet. Step through or jump to traceback to fill the knapsack!

ITEMS IN INPUT (4)

Guitar
Ratio: 1500.0 v/w
w:1|v:1500
Laptop
Ratio: 666.7 v/w
w:3|v:2000
Stereo
Ratio: 750.0 v/w
w:4|v:3000
Camera
Ratio: 2000.0 v/w
w:1|v:2000
knapsack-01.js
1function knapsack01(items, capacity) {
2 const n = items.length;
3 const dp = Array(n + 1).fill(0).map(() => Array(capacity + 1).fill(0));
4 
5 for (let i = 1; i <= n; i++) {
6 const { weight, value } = items[i - 1];
7 for (let w = 0; w <= capacity; w++) {
8 if (weight > w) {
9 dp[i][w] = dp[i - 1][w]; // Item too heavy
10 } else {
11 const exclude = dp[i - 1][w];
12 const include = value + dp[i - 1][w - weight];
13 dp[i][w] = Math.max(exclude, include);
14 }
15 }
16 }
17 
18 // Traceback optimal solution
19 let w = capacity, selected = [];
20 for (let i = n; i > 0 && w > 0; i--) {
21 if (dp[i][w] !== dp[i - 1][w]) {
22 selected.push(items[i - 1]);
23 w -= items[i - 1].weight;
24 }
25 }
26 return { maxValue: dp[n][capacity], selected };
27}
←Previous Algorithm
Fibonacci (Memoization)
Dynamic ProgrammingO(n)
Next Algorithm→
Longest Common Subsequence
O(m·n)Dynamic Programming