Dynamic Programming21 sections · 915 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 i−1i-1 with the same capacity. That's dp[i−1][w]dp[i-1][w].

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