Unbounded knapsack
Pattern: Subsequences and knapsack
Like 0/1 knapsack, but each item can be taken any number of times. Loop capacity upwards, so best[c - w] may already include the same item.
The problem
Given weights, values and a capacity W, return the most value with total weight at most W, using each item any number of times.
Think first
- What changes from 0/1?
- How does the loop direction allow reuse?
- Is there a greedy shortcut?
Hints
Brute force, and why it fails
Try every count of every item: exponential.
The key insight
One upward pass per item allows any number of copies.
Dry run
wt [2, 4, 6], val [5, 11, 13], W = 10.
Step 1 of 2
The plan
best = zeros(W + 1)
for each item: for c from w up to W: best[c] = max(best[c], best[c - w] + v)
Complexity
- Time
O(n × W)- Space
O(W)
One row.
Edge cases
- Nothing fits: 0.
- W = 0.
- One item fits many times.
I've built my logic, show the code
Java
class Solution {
public int unboundedKnapsack(int[] wt, int[] val, int W) {
int[] best = new int[W + 1]; // best[c]: the most value with capacity c, items reusable
for (int c = 1; c <= W; c++)
for (int i = 0; i < wt.length; i++)
if (wt[i] <= c) best[c] = Math.max(best[c], best[c - wt[i]] + val[i]); // the last item packed was i
return best[W];
}
}C++
class Solution {
public:
int unboundedKnapsack(vector<int>& wt, vector<int>& val, int W) {
vector<int> best(W + 1, 0); // best[c]: the most value with capacity c, items reusable
for (int c = 1; c <= W; c++)
for (size_t i = 0; i < wt.size(); i++)
if (wt[i] <= c) best[c] = max(best[c], best[c - wt[i]] + val[i]); // the last item packed was i
return best[W];
}
};Python
class Solution:
def unboundedKnapsack(self, wt: list[int], val: list[int], W: int) -> int:
best = [0] * (W + 1) # best[c]: the most value with capacity c, items reusable
for c in range(1, W + 1):
for w, v in zip(wt, val):
if w <= c:
best[c] = max(best[c], best[c - w] + v) # the last item packed was this one
return best[W]Common mistakes
- Looping downwards.
- Greedy by ratio.