Overview
Unlike 0/1 Knapsack where you can only use an item once, Unbounded Knapsack allows you to pick an item as many times as you want as long as it fits.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Given weights and values of items, put them in a knapsack of capacity W to get the maximum value. You are allowed to use an unlimited number of instances of an item.
Unlike 0/1 Knapsack where you can only use an item once, Unbounded Knapsack allows you to pick an item as many times as you want as long as it fits.
We use a 1D array `dp` of size `W + 1`. `dp[w]` stores the maximum value achievable with a knapsack capacity of exactly `w`.
For a capacity `w`, we try adding every item `i`. If `wt[i] <= w`, the new value is `dp[w - wt[i]] + val[i]`. We take the max over all items.
Unlike 1D 0/1 Knapsack which iterates the capacity backwards, we iterate forwards. This is because we *want* to be able to reuse the same item multiple times (e.g., to compute `dp[w]`, we can use the already-updated `dp[w - wt[i]]`).