AlgoTales · Roadmap

Fractional knapsack

Intermediate · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Fractional knapsack fills a limited space with items you may split, to get the most value. Because splitting is allowed, you simply take items in order of value per unit of space until the bag is full.

Practical use cases

  • Web app: Splitting a limited ad budget. A marketing tool has Rs 10,000 and several channels, each with a return per rupee spent. Sorting channels by return per rupee and funding the best first, down to the last rupee, maximises expected clicks. The manager can explain the split in one line: "every rupee went where it earned the most", and the report can show each channel share.
  • Web app: Cloud storage tiers. A backup service has 500 GB of fast disk and files of different importance. Putting the highest value per GB first, and splitting by file blocks, keeps the most important data on the fast tier. Less important data goes to slower, cheaper storage, so the bill goes down while the data people open daily still loads fast.
  • Web app: Ad slot packing on a page. A news page has a fixed height for sponsored content, and ads can be shown at various sizes. Allotting space by revenue per pixel gives the highest earnings for the layout.
  • System: Resource allocation. Schedulers share CPU time or bandwidth among tasks by value per unit and can hand out any fraction. Because parts can be taken, the rule is very simple: rank by value per unit, take the best, and take just a slice of the last one.

The story: Raju and the Spice Sacks

Raju's cousin ran a spice shop and needed help carrying goods to the market. The delivery bag could hold exactly 50 kilos. On the counter lay three sacks: saffron-mix worth ₹60 (10 kg), cardamom worth ₹100 (20 kg), and cumin worth ₹120 (30 kg).

Raju thought: "The cumin sack is worth the most. I will take it first!" He put it in, then added the cardamom. The bag was full at 50 kg and held ₹220. But Mira, counting on her fingers, said: "Look at the price per kilo instead. Saffron-mix gives ₹6 each kilo, cardamom ₹5, cumin only ₹4."

There was one more rule, and it changed everything: the cousin said, "You may open a sack and carry only part of it." Now Raju took the saffron mix (10 kg) and all the cardamom (20 kg), and the last 20 kg of room were filled with two thirds of the cumin sack. Total: ₹240, better than ₹220!

That is the fractional knapsack: sort by value per kilo, take the best rates first, and break the last item to fill the bag. Warning: if sacks cannot be broken (the 0/1 knapsack), this greedy trick can fail, and we need dynamic programming instead.

How to spot this problem, and where you need it

You have limited capacity (money, space, time) and many options with different value and size, and you can take any fraction of an option, so you want the best mix.

Signs you need it

  • The wording is "maximise value within a limit" and amounts can be divided, such as budget, liquid, bandwidth, hours.
  • Each item has a value and a weight, and the ratio of value to weight is easy to compute.
  • Trying all combinations is unnecessary since parts can be taken.

Where to use it in a project

  • Budget allocation across ad campaigns, sales channels or projects, where each rupee should go to the best return first.
  • Allocating limited storage, bandwidth or CPU share by value per unit.

The solution

Compute value divided by weight for every item. Sort the items from highest ratio to lowest. Take whole items while they fit. When the next item does not fit, take just the fraction that fills the remaining space and stop. Because every unit of space is used at the best available rate, no other mix can beat the total.

Payoff: Before: an even ad split yielding 400 clicks. After: ratio-first allocation yields 560 clicks for the same Rs 10,000.

Explain it like I am 8

Imagine filling a jar with sand, gold dust and stones, and you can scoop any amount. To get the most treasure, fill the jar with the most valuable stuff per scoop first. Since you can take just a little, the jar always ends up perfectly full.

How it works, step by step

  1. For each item, compute its rate: value divided by weight.
  2. Sort the items from the highest rate to the lowest.
  3. Go down the list. If the whole item fits, take all of it and reduce the room.
  4. If it does not fit, take just the part that fits (a fraction), then stop: the bag is full.
  5. Add up the value you collected along the way.

The code in four languages

PHP

<?php
// items: [value, weight]. Parts of an item may be taken.
function fractionalKnapsack(array $items, float $capacity): float {
    // best value per kilo first
    usort($items, fn($a, $b) => ($b[0] / $b[1]) <=> ($a[0] / $a[1]));
    $total = 0;
    foreach ($items as [$value, $weight]) {
        if ($capacity <= 0) break;                 // bag is full
        $take = min($weight, $capacity);           // whole item, or whatever fits
        $total += $value * $take / $weight;        // proportional value
        $capacity -= $take;
    }
    return $total;
}

echo fractionalKnapsack([[60, 10], [100, 20], [120, 30]], 50);   // 240

JavaScript

// items: [value, weight]. Parts of an item may be taken.
function fractionalKnapsack(items, capacity) {
  // best value per kilo first
  items = [...items].sort((a, b) => (b[0] / b[1]) - (a[0] / a[1]));
  let total = 0;
  for (const [value, weight] of items) {
    if (capacity <= 0) break;                      // bag is full
    const take = Math.min(weight, capacity);       // whole item, or whatever fits
    total += value * take / weight;                // proportional value
    capacity -= take;
  }
  return total;
}

console.log(fractionalKnapsack([[60, 10], [100, 20], [120, 30]], 50));   // 240

Java

import java.util.*;

public class Main {
    // items: {value, weight}. Parts of an item may be taken.
    static double fractionalKnapsack(int[][] items, double capacity) {
        int[][] sorted = items.clone();
        // best value per kilo first
        Arrays.sort(sorted, (a, b) -> Double.compare((double) b[0] / b[1], (double) a[0] / a[1]));
        double total = 0;
        for (int[] item : sorted) {
            int value = item[0], weight = item[1];
            if (capacity <= 0) break;                  // bag is full
            double take = Math.min(weight, capacity);  // whole item, or whatever fits
            total += value * take / weight;            // proportional value
            capacity -= take;
        }
        return total;
    }

    public static void main(String[] args) {
        System.out.println(fractionalKnapsack(new int[][]{{60, 10}, {100, 20}, {120, 30}}, 50));   // 240.0
    }
}

Go

package main

import (
	"cmp"
	"fmt"
	"slices"
)

// fractionalKnapsack takes items as [value, weight]. Parts of an item may be taken.
func fractionalKnapsack(items [][2]float64, capacity float64) float64 {
	sorted := slices.Clone(items)
	// best value per kilo first
	slices.SortFunc(sorted, func(a, b [2]float64) int {
		return cmp.Compare(b[0]/b[1], a[0]/a[1])
	})
	total := 0.0
	for _, item := range sorted {
		value, weight := item[0], item[1]
		if capacity <= 0 {
			break // bag is full
		}
		take := min(weight, capacity)  // whole item, or whatever fits
		total += value * take / weight // proportional value
		capacity -= take
	}
	return total
}

func main() {
	fmt.Println(fractionalKnapsack([][2]float64{{60, 10}, {100, 20}, {120, 30}}, 50)) // 240
}

Time: O(n log n) · Extra space: O(1). Sorting by rate dominates; the single pass afterwards is O(n). Extra space is tiny (besides the sort).

Watch out for

  • Sorting by total value instead of value per weight.
  • Using this greedy for the 0/1 knapsack (no breaking). There it can give a wrong answer; use dynamic programming.
  • Dividing by zero weight, or forgetting to stop once the capacity reaches zero.

Quick check

  1. What should items be sorted by?
    • Value per unit weight
    • Total value
    • Weight
  2. Raju's bag has 20 kg left and the next sack weighs 30 kg. What happens in fractional knapsack?
    • Skip the sack
    • Throw something out
    • Take 20/30 of it and finish
  3. Does the same greedy rule always work if items cannot be split?
    • Yes
    • No, the 0/1 knapsack needs another method
    • Only for 3 items