Dynamic Programming21 sections · 916 units
Open in Course

0/1 Knapsack - Transition

Take or skip

For each item ii and capacity ww, you have two choices:

1.1. Skip item ii: Keep the best value from items 11 to i1i-1 with the same capacity. That's dp[i1][w]dp[i-1][w].

2.2. Take item ii: Add viv_i to the best value from items 11 to i1i-1 with reduced capacity wwiw - w_i. That's dp[i1][wwi]+vidp[i-1][w-w_i] + v_i. You can only take item ii if it fits: wiww_i \le w. The transition (the formula to compute each state) is: dp[i][w]=max(dp[i1][w],dp[i1][wwi]+vi)dp[i][w] = \max(dp[i-1][w], dp[i-1][w-w_i] + v_i) if wiww_i \le w, else dp[i][w]=dp[i1][w]dp[i][w] = dp[i-1][w].