Unbounded knapsack
Standard · Write code · about 12 min
Item i weighs weights[i] and is worth values[i]. You may take any number of copies of every item. The bag holds total weight at most capacity.
Return the largest total value that fits.
Example 1
Input:
[[1,3,4],[10,40,50],6]
Output:
80
Two copies of B weigh 6 and are worth 80.
Example 2
Input:
[[2,3],[3,5],4]
Output:
6
Two copies of A beat one B.
Constraints
- 1 ≤ n ≤ 200, where n = weights.length = values.length
- 1 ≤ weights[i] ≤ 200
- 0 ≤ values[i] ≤ 200
- 0 ≤ capacity ≤ 200
Learn the idea first: 0/1 and unbounded knapsack, a visual lesson.
More 0/1 and unbounded knapsack problems
- Fill the knapsack table Warm-up
- Take or skip? Warm-up
- 0/1 knapsack Standard
- Partition equal subset sum Standard
- Spot the bug: one-row 0/1 knapsack Standard
- Target sum Challenge