4. 0/1 KNAPSACK PROBLEM
The 0/1 Knapsack Problem is a
classical dynamic programming
problem.
The goal is to maximize the value
of a Knapsack that can hold at most W
units.
5. Contd…
The objective is to
maximize the profit:-
• The capacity of the
bag is C.
• We have n items.
• The ith item has Value
vi and Weight wi.
6. ALGORITHM
for w = 0 to w
V[0,w] = 0 O(W)
for i = 1 to n
V[i ,0] = 0 O(n)
for i = 1 to n // Repeat n times
for w = 1 to w
if wi <= w O(W)
//item i can be part of
the solution
7. If bi + V[i-1,w-wi] > V[i-1,w]
V[i,w] = bi + V[i-1,w-wi]
Else
V[i,w] = V[i-1,w]
Else
V[i,w] = V[i-1,w] //wi > w
14. The Maximum profit is 6.
The formula for filling a
particular value of the cell:
“m[i,w] = max( m[i-1,w], m[i-
1,w-w[i] ] + p[i] ) “
Eg:
m(4,7) = max( m[3,7] , m[3,
7-6]+ 1)
m(4,7) = max(5,0+1)
m(4,7) = max(5,1)
=> 5