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

Greedy

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). The greedy strategy: always take as much as possible of the item with the highest value-per-weight ratio first.

How Fractional Knapsack Works

  1. Calculate the value-to-weight ratio for every item.
  2. Sort items in descending order of this ratio.
  3. Go through items in that order, taking the entire item if it fits within the remaining capacity.
  4. If an item doesn't fully fit, take only the fraction of it that fills the remaining capacity exactly, then stop.
  5. 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.

Fractional KnapsackO(n log n)
Take the highest value-per-weight items, fractions allowed.
itemvalueweightratiotake %
AA60106.00—
BB100205.00—
CC120304.00—
capacity50
value0
Step 1 / 5
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Fractional Knapsack: capacity 50. Greedy picks the best value/weight ratio first.
Python · Greedy Algorithms in Code
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 total

Behind 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

BestO(n log n) — dominated by the sort
AverageO(n log n)
WorstO(n log n)
SpaceO(1) extra beyond sorting

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.