Dyn Prog Knapsack
Dyn Prog Knapsack
Let Sk be the optimal subset of elements from {I0, I1,... Ik}. But
what we find is that the optimal subset from the elements {I0,
I1,... Ik+1} may not correspond to the optimal subset of elements
from {I0, I1,... Ik} in any regular pattern. Basically, the solution
to the optimization problem for Sk+1 might NOT contain the
optimal solution from problem Sk.
To illustrate this, consider the following example:
The best set of items from {I0, I1, I2} is {I0, I1, I2} but the best
set of items from {I0, I1, I2, I3} is {I0, I2, I3}. In this example,
note that this optimal solution, {I0, I2, I3}, does NOT build upon
the previous optimal solution, {I0, I1, I2}. (Instead it build's
upon the solution, {I0, I2}, which is really the optimal subset of
{I0, I1, I2} with weight 12 or less.)
OR
i Item wi vi
0 I0 4 6
1 I1 2 4
2 I2 3 5
3 I3 1 3
4 I4 6 9
5 I5 4 7
W = 10
Item 0 1 2 3 4 5 6 7 8 9 10
0 0 0 0 0 6 6 6 6 6 6 6
1 0 0 4 4 6 6 10 10 10 10 10
2 0 0 4 5 6 9 10 11 11 15 15
3 0 3 4 7 8 9 12 13 14 15 18
4 0 3 4 7 8 9 12 13 14 16 18
5 0 3 4 7 8 10 12 14 15 16 19
How do we allow taking unlimited copies of an item?
Running the inner loop forwards will do the trick, since every
previous item in the dp array has already been updated
potentially using a copy of item k. This means that multiple
copies of k can build up, if this is optimal.