DPDynamic Programming

Unbounded Knapsack

Maximize value under a capacity when every item may be taken any number of times — the 0/1 loop run forward.

Learn Unbounded Knapsack →
2/3
0
3/5
1
5/9
2
0123456789
0000000000
1/22A single row suffices because each item may be used any number of times: dp[c] may depend on dp[c - w] from the same row. Start with all zeros.
Cell being filledDependency readBase caseComputedReconstructed choice
1dp[0..W] = 0
2for c in 1 .. W:
3 for each item i with w[i] <= c:
4 dp[c] = max(dp[c], dp[c-w[i]] + v[i])
5return dp[W]
Variables
W9
Complexity
best O(n·W)
avg O(n·W)
worst O(n·W)
space O(W)
Speed