Knapsack
Knapsack
Consider-
Knapsack weight capacity = w
Number of items each having some weight and value = n
Start filling the table row wise top to bottom from left to right.
Here, T(i , j) = maximum value of the selected items if we can take items 1 to i and
have weight restrictions of j.
This step leads to completely filling the table.
Then, value of the last box represents the maximum possible value that can be put
into the knapsack.
Step-03:
To identify the items that must be put into the knapsack to obtain that
maximum profit,
• Each entry of the table requires constant time θ(1) for its computation.
• It takes θ(nw) time to fill (n+1)(w+1) table entries.
• It takes θ(n) time for tracing the solution since tracing process traces the n
rows.
• Thus, overall θ(nw) time is taken to solve 0/1 knapsack problem using
dynamic programming.
Problem
Find the optimal solution for the 0/1 knapsack problem making use of
dynamic programming approach. Consider-
Given
n=4
w = 5 kg
(w1, w2, w3, w4) = (2, 3, 4, 5)
(b1, b2, b3, b4) = (3, 4, 5, 6)
Solution-
Given-
Knapsack capacity (w) = 5 kg
Number of items (n) = 4
Step-01:
Draw a table say ‘T’ with (n+1) = 4 + 1 = 5 number of rows and (w+1) = 5 + 1 = 6
number of columns.
Fill all the boxes of 0th row and 0th column with 0.
Step-02:
Start filling the table row wise top to bottom from left to right using the formula-
Finding T(1,1)-
We have,
i=1
j=1
(value)i = (value)1 = 3
(weight)i = (weight)1 = 2
Substituting the values, we get-
n=4
w = 5 kg
T(1,1) = max { T(1-1 , 1) , 3 + T(1-1 , 1-2) } (w1, w2, w3, w4) = (2, 3, 4, 5)
(b1, b2, b3, b4) = (3, 4, 5, 6)
T(1,1) = 0
Finding T(1,2)-
We have,
i=1
j=2
(value)i = (value)1 = 3
(weight)i = (weight)1 = 2
Substituting the values, we get-
T(1,2) = 3
Finding T(1,4)-
We have,
i=1
j=4
(value)i = (value)1 = 3
(weight)i = (weight)1 = 2
T(1,4) = 3
We have,
i=1
j=5
(value)i = (value)1 = 3
(weight)i = (weight)1 = 2
T(1,5) = 3
Finding T(2,5)-
We have,
i=2
j=5
(value)i = (value)2 = 4
(weight)i = (weight)2 = 3
T(2,5) = 7
Similarly, compute all the entries.
After all the entries are computed and filled in the table, we get the following table-
The last entry represents the maximum possible value that can be
put into the knapsack.
So, maximum possible value that can be put into the knapsack = 7.
Following Step-04,