M2 Dynamic Programming - 0-1 Knapsack Problem
M2 Dynamic Programming - 0-1 Knapsack Problem
Procedure
• Step-01:
• Draw a table say ‘T’ with (n+1) number of rows and (w+1) number of columns.
Fill all the boxes of 0th row and 0th column with zeroes.
• Step-02:
• Start filling the table row wise top to bottom from left to right.
• Use the following formula-
• 𝑇 (𝑖 , 𝑗) = max{ 𝑇 ( 𝑖 − 1 , 𝑗 ) , 𝑣𝑎𝑙𝑢𝑒𝑖 + 𝑇( 𝑖 − 1 , 𝑗 – 𝑤𝑒𝑖𝑔ℎ𝑡𝑖 ) }
• Here, 𝑇(𝑖 , 𝑗) = maximum value of the selected items if we can take items 1 𝑡𝑜 𝑖 and
have weight restrictions of 𝑗.
• Step-03:
• To identify the items that must be put into the knapsack to obtain that maximum profit,
• Consider the last column of the table.
• Start scanning the entries from bottom to top.
• On encountering an entry whose value is not same as the value stored in the entry
immediately above it, mark the row label of that entry.
• After all the entries are scanned, the marked labels represent the items that must
• EXAMPLE:
• Find the optimal solution for the 0/1 knapsack problem making use of dynamic
programming approach. Consider n = 4, w = 5 kg, (w1, w2, w3, w4) = (2, 3, 4, 5),
(b1, b2, b3, b4) = (3, 4, 5, 6)
T 0 1 2 3 4 5
ITEM WEIG VALU
HT E 0 0 0 0 0 0 0
1 2 3 1 0
2 3 4 2 0
3 4 5 3 0
4 5 6 4 0
T 0 1 2 3 4 5
0 0 0 0 0 0 0
1 0
2 0
3 0
4 0
Dynamic Programming Page 3
2 0
3 0
4 0
T 0 1 2 3 4 5
0 0 0 0 0 0 0
1 0
2 0
3 0
4 0