Greedy Knapsack
Greedy Knapsack
The i-th object has positive weight wi and positive unit value vi .
The objects are sorted in increasing order of (*) · · ·
The knapsack capacity is C. for i := 1 to n do
We wish to select a set of proportions of objects to put in the knapsack so that x[i] := 0
the total values is maximum and without breaking the knapsack. end for;
weight := 0; i := 1;
while weight < M ∧ i 6 n do
if weight + w[i] 6 M
then x[i] := 1; weight := weight + w[i];
else x[i] := (M − weight)/w[i]; weight := M
end if ;
i := i + 1
end while;
return (x)
end
w 10 20 30 40 50
v 20 30 66 40 60
Select always the most valuable object Select always the object with highest ratio value/weight
object 1 2 3 4 5 object 1 2 3 4 5
selected 0 0 1 0.5 1 ratio 2.0 1.5 2.2 1.0 1.2
Total selected weight 100 and total value 146. selected 1 1 1 0 0.8
Total selected weight 100 and total value 164.
Input: 5 objects, C = 100
therefore
n
X n
X
xi wi − yi wi > 0.
Theorem: The greedy algorithm that always selects the lighter object does not i=1 i=1
always find an optimal solution to the Fractional Knapsack problem. Let V (Z) denote the total value of a feasible solution.
n n
X X vi
V (X) − V (Y ) = (xi − yi )vi = (xi − yi )wi .
i=1 i=1
wi
vi vj
Theorem: The greedy algorithm that always selects the object with better ratio If i < j, xi = 1 then xi − yi > 0 and wi > wj and we have
value/weight always finds an optimal solution to the Fractional Knapsack problem.
vi vj
(xi − yi ) > (xi − yi )
Proof. Assume that the objects are {1, . . . , n} and that wi wj
v1 v2 vn
> > ··· > . vi vj
w1 w2 wn If i > j, xi = 0 then xi − yi 6 0 but wi 6 wj therefore
vi vj
(xi − yi ) > (xi − yi )
Let X = (x1 , . . . , xn ) be the solution computed by the greedy algorithm. wi wj
The objects are sorted in increasing order of (*) · · · Let v[i, j] be the maximum value we can get from objects {1, 2, . . . , i} and taking a
for i := 1 to n do maximum weight of 0 6 j 6 W .
x[i] := 0
end for;
We wish to compute v[n, W ].
weight := 0; i := 1; To compute v[i, j] we have two possibilities: The i-th element is or is not part of
while weight < M ∧ i 6 n do
the solution.
if weight + w[i] 6 M
then x[i] := 1; weight := weight + w[i]; This gives the recurrence,
end if ;
i := i + 1 v[i − 1, j − w ] + v if the i-th element is part of the solution
i i
end while; v[i, j] =
v[i − 1, j] otherwise
return (x)
end