Learn / Greedy

Fractional knapsack

When items can be split, take them in order of value per unit of weight, and take a part of the last one that does not fit. When the choice is about cheap things to buy with a budget, buy the cheapest first, up to any limit each one has.

How to recognise it

  • Items can be taken in part.
  • A fixed budget or capacity, and each unit of something has a price or value.
  • Ratios: value per kilogram, cost per item.

Best ratio first

sort items by value / weight, highest first
for each item:
    take = min(weight, capacity left)
    total += value * take / weight

Any unit of weight is best filled with the most valuable material available; that is the whole proof.

Cheapest first

When every unit you buy counts the same, the cheapest ones are best. If each option has a limit (at most i stocks on day i), buy as many as the limit and the budget allow, cheapest first.

Common mistakes

  • Comparing ratios with integer division.
  • Using this for whole items (0/1 knapsack).

Problems

0 of 2 solved

Check yourself

Capacity 50, items (value 60, weight 10), (100, 20), (120, 30). Best value?

Why does this greedy fail for the 0/1 knapsack?

In Buy Maximum Stocks, which day do you buy from first?