1. Capacity table
dp[cap] is best value for that capacity.
Array(capacity + 1).fill(0)Typorithm · medium
Step 1 of 8 · intro card
Dynamic Programming
0/1 Knapsack chooses the best value under a capacity when each item can be taken once.
The state is best value for a capacity.
Each item updates possible capacities.
Reverse capacity iteration keeps the item single-use.
State: best value at capacity.
Choice: skip item or take item.
Reverse loop enforces 0/1 usage.
Time O(n*capacity).
function knapsack(weights, values, capacity) {
const dp = Array(capacity + 1).fill(0);
for (let i = 0; i < weights.length; i++) {
for (let cap = capacity; cap >= weights[i]; cap--) {
dp[cap] = Math.max(dp[cap], dp[cap - weights[i]] + values[i]);
}
}
return dp[capacity];
}Connect each part of the code to the concept before you type.
dp[cap] is best value for that capacity.
Array(capacity + 1).fill(0)Each item can be used at most once.
for (let i = 0; i < weights.length; i++)Reverse order prevents reusing the same item twice.
for (let cap = capacity; cap >= weights[i]; cap--)Compare skipping item with taking it.
dp[cap] = Math.max(dp[cap], dp[cap - weights[i]] + values[i])Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputWeights 2,3,4 · values 4,5,7 · capacity 6
Follow temporary values, local state and supporting structures at this step.
↗ The 7-cell working table above is itself auxiliary memory. Input values are shown separately.
Values3 entries
Input · not auxiliary memory
Weights3 entries
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state