Dynamic Programming21 sections · 916 units
Open in Course

0/1 Knapsack - Walkthrough

Tracing the algorithm

Let's trace 0/1 Knapsack with items [(w=2,v=3),(w=3,v=4),(w=4,v=5)][(w=2, v=3), (w=3, v=4), (w=4, v=5)] and capacity W=5W=5. Build the DP table row by row.

After item 1: dp[2]=3dp[2]=3.

After item 2: dp[3]=4dp[3]=4, dp[5]=7dp[5]=7 (take both).

After item 3: dp[4]=5dp[4]=5, dp[5]=max(7,5)=7dp[5]=\max(7, 5)=7. The answer is dp[5]=7dp[5]=7. We took items 1 and 2 (weights 2+3=52+3=5, values 3+4=73+4=7). Item 3 doesn't fit with either of them. Notice how each cell considers: skip this item (keep previous value) or take it (add value, subtract weight). This is the core of all knapsack variants.