Data Structures & Algorithms

Table of Contents

Knapsack01

Problem

Set of elements with a benefit and weight, and a total maximum weight. Have to find highest possible benefit.

W  = 5

SBW
121
252
343

Solution

Initialise a table:

w (b) \ W012345
0000000
1 (2)0
2 (5)0
3 (4)0RESULT

For each cell, in row with weight n: value = max{ b(n) + b(one row up, n columns to left), value in cell above }

w (b) \ W012345
0000000
1 (2)0<= 2<= 2<= 2<= 2<= 2
2 (5)0^ 2<= 5<= 7<= 7<= 7
3 (4)0^ 2^ 5^ 7^ 7<= 9

So the maximum benefit is 9.

To find the items that were taken, retrace:

Here, the items were 3 and 2.

https://www.youtube.com/watch?v=8LusJS5-AGo

Complexity