3. KNAPSACK PROBLEM
Now the problem is that If we have a knapsack that only can hold 20 kg
of weight. Which items to be select that volume doesn't exceeds 20 kg
but have the high value?
4. KNAPSACK PROBLEM
In this case the problem is known as 0/1 knapsack problem because we
will either select an item or either reject in item.
0 1
5. Brute Force approach to solve this problem
• First we will create all possible outcomes of the items.
• Then we will select the best one which weight doesn’t exceeds from
20 kg but have the maximum value.
Clock Frame Radio Jar Book PC
Value $175 $90 $20 $50 $10 $200
Weight 10 kg 9 kg 4 kg 2 kg 1 kg 20 kg
6. (1) We can select
Total weight = 20 kg
Total value = 275 $
Total weight = 17 kg
Total value = 255 $
7. Total weight = 16 kg
Total value = 170 $
Total weight = 20 kg
Total value = 200 $
8. Now after having all combinations of items we can say that option no 1
is best to choose.
Because in that option we have exactly 20 kg of weight which the
knapsack can hold with the highest volume.
Total weight = 20 kg
Total value = 275 $
9. 0-1 Knapsack problem
•Given a knapsack with maximum capacity W, and a set S consisting of
n items
•Each item i has some weight wi and benefit value bi (all wi , bi and W
are integer values)
•Problem: How to pack the knapsack to achieve maximum total value
of packed items?
•Solution: Dynamic Programming.
10. Fractional Knapsack Problem
• We are given n objects and a knapsack. Object i has a weight wi
and the knapsack has a capacity m.
• If a fraction xi, 0<=xi <=1, of object i is placed into the knapsack,
then a profit pi xi is earned.
• The objective is to obtain a filling of the knapsack that maximizes
the total profit earned.
11. Greedy Algorithm gives the optimal solution
• Greedy-fractional-knapsack (w, v, W)
1. for i =1 to n
2. do x[i] =0
3. weight = 0
4. while weight < W
5. do i = best remaining item
6. if weight + w[i] ≤ W
7. then x[i] = 1
8. weight = weight + w[i]
9. else
10. x[i] = (w - weight) / w[i]
11. weight = W
12. return x
12. Analysis
•If the items are already sorted into decreasing order of vi / wi , then
the while-loop takes a time in O(n);
•Therefore, the total time including the sort is in O(n log n).
•If we keep the items in heap with largest vi/wi at the root. Then
creating the heap takes O(n) time
•while-loop now takes O(log n) time (since heap property must be
restored after the removal of root)