Professional Documents
Culture Documents
Greedy Fractional Knapsack
Greedy Fractional Knapsack
• Value/Weight Ratio
A (60/20=3), B (100/20=5), C=(120/30=4)
Example 1
Item B C A
Value or Profit 100 120 60
Output: Weight 20 30 20
Value/weight 5 4 3
Taking B
• Profit = 100
• Remaining Capacity = 30
Taking C
• Profit = 100 + 120 = 220
• Remaining Capacity = 0
Considering Item A
Since, Wight of A > Remaining Capacity we can not take A
Total profit = 220
Item A B C
Example 2 Value or Profit 60 100 120
Weight 20 20 30
• Input:
Items as (value, weight) pairs
• Value/Weight Ratio
A (60/20=3), B (100/20=5), C=(120/30=4)
Example 2
Item B C A
Value or Profit 100 120 60
Output: Weight 20 30 20
Taking B Value/weight 5 4 3
• Profit = 100
• Remaining Capacity = 40
Taking C
• Profit = 100 + 120 = 220
• Remaining Capacity = 10
Taking A
Since, Weight of A > Remaining Capacity we can not take A completely, only 10/20 can be taken in
to the sack.
Total profit = 220 + (10/20)*60 = 220 + 30 = 250.
Fractional Knapsack Problem - Complexity
In the solution we use a heap-based PQ to store the items of S, where the
key of each item is its value index
With PQ, each greedy choice, which removes an item with the greatest
value index, takes O(log n) time
The fractional knapsack algorithm can be implemented in time O(n log n).