Overview
This is the definitive DP problem. At each item, you make a choice: take it, or leave it. If you take it, you lose capacity `wt[i]` but gain `val[i]`.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Given N items with weights and values, find the maximum value you can fit into a knapsack of capacity W. You can either pick an item (1) or not pick it (0). No duplicates allowed!
This is the definitive DP problem. At each item, you make a choice: take it, or leave it. If you take it, you lose capacity `wt[i]` but gain `val[i]`.
Using a 1D array, `dp[w]` stores the maximum value achievable with a knapsack capacity of exactly `w`.
When considering item `i` at capacity `w`, the best choice is `max(dp[w] (leave it), dp[w - wt[i]] + val[i] (take it))`.
Because we use a 1D array and can only use each item ONCE, the capacity loop MUST run backwards from `W` down to `wt[i]`. If it ran forwards, we might use the same item multiple times!