Fractional Knapsack — The Smart Thief Strategy 🕵️

Problem idea

Thief with knapsack

A thief has a knapsack of limited capacity W. Each item has value v and weight w. Unlike 0/1 knapsack, the thief may take fractions of items.

Greedy rule

Sort items by value density (v / w) in descending order. Take items fully while they fit; otherwise take the fraction that fits.

Why greedy works here

  • Fractions smooth the solution space.
  • Taking the best density first can never reduce the optimal value.
  • Greedy-choice property and optimal substructure both hold.
Greedy-choice ✔
Optimal substructure ✔

Contrast

In 0/1 knapsack, fractions are not allowed. Early greedy choices can block better combinations, so dynamic programming is required.

Knapsack capacity
W = 50
Used = 0  |  Remaining = 50
Total value = 0

Click Start to begin filling the bag using the greedy rule.

Item Value Weight v/w Decision
A60106.0
B100205.0
C120304.0
Result
Greedy takes A and B fully, then takes a fraction of C to exactly fill the remaining capacity.
Final: value = 240, weight used = 50.
Advanced (Optional): Try your own data Up to 6 items

Change capacity and items, then click Run Greedy to see decisions (full / fraction) for each item. Items are sorted by value/weight automatically.
⚠️ Some inputs may not require a fraction. Greedy still works, but the ✂️ step may not appear.

Custom capacity
Tip: try W = 40, 55, or change weights to force a fraction.
Custom items (max 6)
Item Value Weight v/w Decision
Sorted order (by value/weight)
Advanced result