0% found this document useful (0 votes)
19 views

Knapsack Algorithm

The 0-1 Knapsack algorithm solves the knapsack problem in pseudo-polynomial time. It uses a 2D table V[n,W] to store optimal solutions, filling it in from left to right and top to bottom. For each item i and weight w, it either includes the item if there is room or keeps the previous solution, running in O(nW) time which is pseudo-polynomial for the knapsack problem. An example applies the algorithm to 4 items with weights and values and a knapsack capacity of 5.

Uploaded by

rrajeshpatel
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Knapsack Algorithm

The 0-1 Knapsack algorithm solves the knapsack problem in pseudo-polynomial time. It uses a 2D table V[n,W] to store optimal solutions, filling it in from left to right and top to bottom. For each item i and weight w, it either includes the item if there is room or keeps the previous solution, running in O(nW) time which is pseudo-polynomial for the knapsack problem. An example applies the algorithm to 4 items with weights and values and a knapsack capacity of 5.

Uploaded by

rrajeshpatel
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 5

0-1 Knapsack Algorithm

0-1 Knapsack Algorithm


for w = 0 to W
V[0,w] = 0
for i = 1 to n
V[i,0] = 0
for i = 1 to n
for w = 0 to W
if wi <= w // item i can be part of the solution
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
Running time
for w = 0 to W
V[0,w] = 0 O(W)
for i = 1 to n
V[i,0] = 0
for i = 1 to n Repeat n times
for w = 0 to W
< the rest of the code O(W)
>

What is the running time of this algorithm?


O(n*W)
Remember that the brute-force algorithm
takes O(2n)
Example

Lets run our algorithm on the


following data:

n = 4 (# of elements)
W = 5 (max weight)
Elements (weight, benefit):
(2,3), (3,4), (4,5), (5,6)
Items:
1: (2,3)
Example 2: (3,4)
3: (4,5)
i\W 0 1 2 3 4 5 i=1 4: (5,6)
0 0 0 0 0 0 0 bi=3
1 0 0
wi=2
2 0
w=1
3 0
w-wi =-1
4 0
if wi <= w // item i can be part of the solution
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

You might also like