Algorithms · Visualized
Fractional Knapsack
Greedy
Make the locally optimal choice at each step, hoping it leads to a globally optimal solution.
Given items with weights and values, and a knapsack with a weight limit, maximize total value when you're allowed to take fractions of an item (unlike 0/1 Knapsack). Time: O(n log n) average, O(n log n) worst; space: O(1) extra beyond sorting.
Big-O: Works when the problem has optimal substructure + greedy-choice property — e.g. intervals, Huffman, fractional knapsack.
Fractional Knapsack
GreedyGiven items with weights and values, and a knapsack with a weight limit, maximize total value when you're allowed to take fractions of an item (unlike 0/1 Knapsack). The greedy strategy: always take as much as possible of the item with the highest value-per-weight ratio first.
How Fractional Knapsack Works
- Calculate the value-to-weight ratio for every item.
- Sort items in descending order of this ratio.
- Go through items in that order, taking the entire item if it fits within the remaining capacity.
- If an item doesn't fully fit, take only the fraction of it that fills the remaining capacity exactly, then stop.
- Sum up the value collected — this is the maximum achievable value.
Fractional Knapsack Worked Example
Input: {items: [{weight: 10, value: 60}, {weight: 20, value: 100}, {weight: 30, value: 120}], capacity: 50}
Ratios: 60/10=6, 100/20=5, 120/30=4. Sorted by ratio: item1(6), item2(5), item3(4). Take all of item1 (weight10, value60), remaining capacity=40. Take all of item2 (weight20, value100), remaining capacity=20. Item3 needs 30 but only 20 remains → take 20/30 = 2/3 of it, value = 2/3×120=80. Total value = 60+100+80 = 240.
| item | value | weight | ratio | take % | |
|---|---|---|---|---|---|
| A | A | 60 | 10 | 6.00 | — |
| B | B | 100 | 20 | 5.00 | — |
| C | C | 120 | 30 | 4.00 | — |
def fractional_knapsack(items, capacity):
items.sort(key=lambda it: it[1] / it[2], reverse=True) # (id, value, weight)
total = 0.0
for _, v, w in items:
if capacity >= w:
total += v
capacity -= w
else:
total += v * (capacity / w)
break
return totalBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Fractional Knapsack Time & Space Complexity
When to Use Fractional Knapsack
- Resource allocation problems where partial usage is allowed, like blending investments, mixing materials, or filling cargo space with divisible goods.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.