Unbounded knapsack
35 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)In unbounded knapsack, items can be chosen an unlimited number of times. We examine the recursive branching pattern first before using the forward loop.
Brute Force Recursion and Infinite Choice Trees
Unbounded knapsack chooses items to get the most value within a weight limit when every item can be taken any number of times.
Unbounded knapsack is the knapsack problem where you can reuse items as many times as you want, unlike 0/1 knapsack where each item is used at most once. Examples include cutting rods, exchanging coins, and purchasing supplies in bulk.
int solve(int[] wt, int[] val, int i, int w) { if (i == wt.length || w == 0) return 0; int skip = solve(wt, val, i + 1, w); // move on to the next item int take = 0; if (wt[i] <= w) { take = val[i] + solve(wt, val, i, w - wt[i]); // stay at i: reuse it } return Math.max(skip, take);}With plain recursion, after picking item i, we do NOT advance to i + 1. Instead, we stay at item i with reduced capacity w - wt[i]: solve(i, w) = max(solve(i + 1, w), val[i] + solve(i, w - wt[i])).
Why is this slow? Because items can be picked repeatedly, the recursion tree branches up to n^W times! For a target amount of 50 and 5 coin denominations, plain recursion creates millions of duplicate function calls.
The Forward Loop Mechanism
In 0/1 knapsack, we looped capacity backward to prevent using an item twice. In unbounded knapsack, we WANT to allow multiple copies of the same item!
Therefore, we iterate capacity forward from wt[i] up to W: dp[w] = Math.max(dp[w], val[i] + dp[w - wt[i]]).
Example 1 · Standard Unbounded Knapsack
public class UnboundedKnapsackDemo { public static int unboundedKnapsack(int[] wt, int[] val, int W) { int[] dp = new int[W + 1]; for (int i = 0; i < wt.length; i++) { for (int w = wt[i]; w <= W; w++) { dp[w] = Math.max(dp[w], dp[w - wt[i]] + val[i]); } } return dp[W]; }
public static void main(String[] args) { int[] wt = {1, 3, 4, 5}; int[] val = {10, 40, 50, 70}; System.out.println("Max value for cap 8: " + unboundedKnapsack(wt, val, 8)); }}Max value for cap 8: 110
What this code does
- Forward inner loop from wt[i] up to W permits multiple copies of item i.
- Picking two copies of item 3 (wt 3, val 40) plus two copies of item 1 (wt 1, val 10) yields 100.
- Best choice takes item 5 (wt 5, val 70) and item 3 (wt 3, val 40) for max value 110.
Because capacity runs forward, when dp[w] reads dp[w - wt[i]], that earlier cell may have already included item i. This naturally chains multiple copies of item i together in O(n * W) time.
Trace the code
Watch the forward loop reuse an item
Step through the program and watch the dp cells.
Variables
- dp
- 0 0 0 0 0 0 0
Output
(nothing printed yet)Line 3dp has 7 cells for capacities 0 to 6, all 0. The one item weighs 2 and is worth 3.
Rod Cutting Equivalence
A rod of length L can be cut into smaller pieces of lengths 1 to L, each with a given selling price. What cuts yield maximum revenue?
Example 2 · Classic Rod Cutting Revenue Maximization
public class RodCuttingDemo { public static int cutRod(int[] prices, int n) { int[] dp = new int[n + 1]; for (int len = 1; len <= n; len++) { int maxVal = Integer.MIN_VALUE; for (int cut = 1; cut <= len; cut++) { maxVal = Math.max(maxVal, prices[cut - 1] + dp[len - cut]); } dp[len] = maxVal; } return dp[n]; }
public static void main(String[] args) { int[] prices = {1, 5, 8, 9, 10, 17, 17, 20}; System.out.println("Max revenue for rod 8: " + cutRod(prices, 8)); }}Max revenue for rod 8: 22
What this code does
- For length 8, cutting into two pieces of length 2 and 6 yields 5 + 17 = 22.
- Subproblems dp[len - cut] solve remainder lengths efficiently.
- Solves rod cutting in O(n^2) time and O(n) space.
This maps directly to unbounded knapsack: the rod length L is the knapsack capacity W, each cut length is an item weight, and the piece price is the item value. The recurrence evaluates dp[len] = Math.max(dp[len], price[i] + dp[len - cutLength[i]]), solving optimal rod cutting in O(L^2) time.
Permutations versus Combinations with Unbounded Items
When counting ways to make change with unlimited coins, loop order completely changes the result.
Outer loop over coins, inner loop over amounts: counts combinations (order does not matter, so {1, 2} and {2, 1} count as 1 way).
Example 3 · Coin Change Minimum Coins via Unbounded Knapsack
import java.util.Arrays;
public class CoinChangeMinCoinsDemo { public static int coinChange(int[] coins, int amount) { int[] dp = new int[amount + 1]; Arrays.fill(dp, amount + 1); dp[0] = 0; for (int c : coins) { for (int a = c; a <= amount; a++) { dp[a] = Math.min(dp[a], dp[a - c] + 1); } } return dp[amount] > amount ? -1 : dp[amount]; }
public static void main(String[] args) { int[] coins = {1, 2, 5}; System.out.println("Min coins for 11: " + coinChange(coins, 11)); }}Min coins for 11: 3
What this code does
- Forward loop from c up to amount allows reusing coin c multiple times.
- Optimal combination uses 5 + 5 + 1 = 3 coins total.
- Unreachable amounts retain initial sentinel value and return -1.
Outer loop over amounts, inner loop over coins: counts permutations (order matters, so {1, 2} and {2, 1} are counted as 2 distinct sequences). Mixing these up is one of the most common mistakes in DP interviews.
Next step
Check your understanding
10 quick questions