Greedy Algorithms8 sections · 316 units
Open in Course

Fractional Knapsack - Implementation

The code

function fractionalKnapsack(items, W)
 sort items by value/weight descending
 totalValue := 0
 remainingCapacity := W
 for each item in items
 if item.weight <= remainingCapacity then
 totalValue := totalValue + item.value
 remainingCapacity := remainingCapacity - item.weight
 else
 fraction := remainingCapacity / item.weight
 totalValue := totalValue + item.value * fraction
 break
 return totalValue

Time: O(nlogn)O(n \log n). Space: O(1)O(1) extra.