The 0/1 Knapsack Problem is a dynamic programming optimization problem that selects a subset of items with given weights and values to maximize total value without exceeding capacity W.
For capacities w=0..1, max value is 0. For w=2..5, include item 1 for total value 3.
Row 1 DP: [0, 0, 3, 3, 3, 3]At w=5, compare excluding item 2 (val 3) vs including item 2 (val 4 + dp[1][5-3]=3 = 7). Max value is 7.
Row 2 DP: [0, 0, 3, 4, 4, 7]At w=5, compare excluding item 3 (val 7) vs including item 3 (val 5 + dp[2][1]=0 = 5). Max remains 7.
Final Max Knapsack Value at DP[3][5]: 7You have a backpack that holds at most 15 kg. You must pick items (laptop, tent, food) to get the maximum total utility without tearing the bag.
500 steps (Linear)
O(N × W) Memoized Time
O(N × W) Cache Matrix
Memory growth rate as N expands.
Relative efficiency rating for large N.
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| DP Grid Computation | O(N × W) | O(N × W) |
function knapsack(W, wt, val, n) {
const dp = Array.from({ length: n + 1 }, () => new Array(W + 1).fill(0));
for (let i = 1; i <= n; i++) {
for (let w = 1; w <= W; w++) {
if (wt[i - 1] <= w) {
dp[i][w] = Math.max(val[i - 1] + dp[i - 1][w - wt[i - 1]], dp[i - 1][w]);
} else {
dp[i][w] = dp[i - 1][w];
}
}
}
return dp[n][W];
}Optimizes cloud server memory allocations within budget caps.
Selects optimal financial investments under risk limits.
Validate your conceptual understanding, operation mechanics, and core concepts of Knapsack.
You can optimize space complexity from O(N × W) down to O(W) by maintaining a 1D DP array traversed in reverse!
0/1 Knapsack loaded. Capacity: 5. Run solver to fill DP cache grid.
Weight: 1
Value: $15
Weight: 2
Value: $20
Weight: 3
Value: $30
| Items \ Weight | w=0 | w=1 | w=2 | w=3 | w=4 | w=5 |
|---|---|---|---|---|---|---|
| 0 (None) | 0 | 0 | 0 | 0 | 0 | 0 |
| Item A | 0 | 0 | 0 | 0 | 0 | 0 |
| Item B | 0 | 0 | 0 | 0 | 0 | 0 |
| Item C | 0 | 0 | 0 | 0 | 0 | 0 |