Greedy Algorithms8 sections · 316 units
Open in Course

Fractional Knapsack - Algorithm

Sort by ratio

Sort items by value/weight ratio (descending). Take items in order until capacity runs out. For the last item that does not fully fit, take a fraction. It works because with fractions, there is no blocking.

You can always squeeze in more value by taking the highest-ratio items first. Time: O(nlogn)O(n \log n). Space: O(1)O(1).