Problem Statement

Unbounded Knapsack

Imagine a backpack that can hold a certain amount of weight, and a shelf of items, each with a weight and a value (think of value as how much money it is worth). You want to pack the backpack so the total value is as high as possible. The twist here is that you have an unlimited supply of every item. You can grab the same item once, twice, ten times, as long as the total weight still fits. That is what "unbounded" means: no limit on how many times you reuse an item. The capacity W is the most weight the backpack can carry. The goal is the biggest total value you can stuff in without going over W. The well-known cousin of this problem is the 0/1 knapsack, where each item can be taken at most once. The trick that makes our version allow repeats is how we walk through the capacities, which we will explain below.

mediumDynamic ProgrammingDynamic ProgrammingTime: O(n * W) · Space: O(W)

Signals to notice

maximize value with unlimited supplyeach item can be used many timescapacity constraint

Brute force first

Try all possible quantities of each item — exponential without memoization. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

The key insight

1D DP: dp[w] = max value achievable with capacity w. For each capacity from 1 to W, try every item: dp[w] = max(dp[w], dp[w-weight[i]] + value[i]). The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

Trace it on weights=[1,3], values=[10,40], W=6

init: dp=[0,0,0,0,0,0,0] (indices 0..6)
item0 (wt=1,val=10): scan w=1..6 forward; each dp[w]=dp[w-1]+10 -> dp=[0,10,20,30,40,50,60]
item1 (wt=3,val=40), w=3: max(dp[3]=30, dp[0]+40=40)=40 -> dp[3]=40
item1, w=4: max(dp[4]=40, dp[1]+40=50)=50 -> dp[4]=50
item1, w=5: max(dp[5]=50, dp[2]+40=60)=60 -> dp[5]=60
item1, w=6: max(dp[6]=60, dp[3]+40=80)=80 (dp[3] already includes item1, reuse OK) -> dp[6]=80
dp=[0,10,20,40,50,60,80]; return dp[6] = 80

What must stay true

Unlike 0/1 knapsack, processing left-to-right in the 1D array ALLOWS reuse — dp[w-weight[i]] may already include item i, and that's correct for unbounded. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Shape of the loop

dp = array of size W+1 filled with 0
for each item i:
    for w from weights[i] to W (forward):   # forward enables reuse
        dp[w] = max(dp[w], dp[w - weights[i]] + values[i])
return dp[W]

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Processing right-to-left like 0/1 knapsack — that prevents reuse. For unbounded, process LEFT-to-RIGHT so items can be picked multiple times. The fix is usually to return to the meaning of each move, not just the steps themselves.

Dynamic Programming Pattern