0-1 Knapsack For Class
0-1 Knapsack For Class
max bi where wi W
iA iA
3 cases:
1. There are no items in the knapsack, or the weight of the knapsack
is 0 - the benefit is 0
2. The weight of itemi exceeds the weight w of the knapsack - itemi
cannot be included in the knapsack and the maximum benefit is
B[i-1, w]
3. Otherwise, the benefit is the maximum achieved by either not
including itemi ( i.e., B[i-1, w]),
or by including itemi (i.e., B[i-1, w-wi]+bi)
0 for i 0 or w 0
B[i, w] B[i 1, w] if w i w
max{ B[i 1, w], B[i 1, w w ] b } otherwise
i i
Pseudo-code:0/1 Knapsack Problem
Matrix Size: (n+1)*(W+1)
Input: {w1 ,w2, . . . wn }, W , {b1 ,b2, ...b
n }
Output: B[n, W],
for w 0 to W do // row 0
B[0,w] 0
for k 1 to n do // rows 1 to n
B[k, 0] 0 // element in column 0
for w 1 to W do // elements in columns 1 to W
if (wk w) and (B[k-1, w- wk ] + bk > B[k-1, w])
then B[k, w] B[k-1, w- wk ] + bk
else B[k, w] B[k-1, w]
Example:
W = 30, S = { ( i1 , 5, $50 ), (i2 ,10, $60 ), ( i3, 20, $140 ) }
Weight: 0 1 2 3 … 30
MaxProfit { } 0 0 0 0 … 0
Weight: 0 1 2 3 4 5 … 30
MaxProfit { } 0 0 0 0 0 0 … 0
MaxProfit{i1} 0 0 0 0 0 50 … 50
Example continued
W = 30, S = { ( i1 , 5, $50 ), (i2 ,10, $60 ), ( i3, 20, $140 ) }