Algorithms · Visualized
DP: Unbounded Knapsack
Dynamic Programming
Break problems into overlapping subproblems and store answers.
The knapsack variant where every item may be taken any number of times. Time: O(n × capacity) average, O(n × capacity) worst; space: O(capacity) — a single rolling row.
Big-O: The most-asked interview category — 35 classics here.
Unbounded Knapsack
Dynamic ProgrammingThe knapsack variant where every item may be taken any number of times. A single row dp[w] is enough: dp[w] holds the best value achievable with capacity exactly w, and each item updates it by looking back at the capacity left after taking one more copy — dp[w - weight]. Because that look-back can already include copies of the same item, repetition happens automatically.
How Unbounded Knapsack Works
- Create a 1D array dp of size (capacity + 1), initialized to 0: with zero capacity, no value is possible.
- For each capacity w from 1 to capacity, examine every item whose weight fits in w.
- For a fitting item, its candidate value is item's value + dp[w − item's weight] — the best way to fill the remaining space, which may already contain more copies of this same item.
- Set dp[w] to the maximum candidate found across all items (or keep dp[w] when nothing fits).
- After the loop finishes, dp[capacity] is the maximum value with unlimited copies of each item.
Unbounded Knapsack Worked Example
Input: {weights: [2, 3, 5], values: [3, 5, 7], capacity: 8}
dp[2]=3 (one w2). dp[3]=5 (one w3). dp[4]=6 (two w2 — repetition!). dp[5]=8 (w2+w3). dp[6]=10 (two w3). dp[8]: take a w3 and look up dp[5] → 5+8=13. Answer dp[8]=13 = one w2 + two w3 items (weight 2+3+3=8, value 3+5+5=13) — impossible in 0/1 knapsack.
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | |
|---|---|---|---|---|---|---|---|---|---|
| best value | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
def unbounded_knapsack(weights, values, capacity):
dp = [0] * (capacity + 1)
for c in range(1, capacity + 1):
for w, v in zip(weights, values):
if w <= c:
dp[c] = max(dp[c], dp[c - w] + v) # same item may repeat
return dp[capacity]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Unbounded Knapsack Time & Space Complexity
When to Use Unbounded Knapsack
- Rod cutting, coin change (maximize/minimize with infinite supply) and sticker/ribbon problems share this exact recurrence.
- Any procurement scenario where purchases are repeatable within a budget: buying multiple units of stock, filling a server with VMs, cutting raw material into pieces.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.