← DiffPush

Fractional Knapsack

Baseline Greedy Approach · Easy O(n log n) · O(1)

The Cargo Lift Value Haul

A cargo lift has a fixed weight budget and a warehouse full of commodity sacks, each with a weight and a resale value. Unlike sealed crates, sacks can be portioned — a fraction of a sack yields that fraction of its value. The loader packs by density, filling the lift with the most value-dense sacks first and taking a partial sack only to cap off the remaining budget.

Input: An integer W (capacity) plus two arrays: values and weights of the items.

Output: Return the maximum total value achievable, allowing fractional takes.

Constraints

Examples

Example 1

Input: {"W":50,"values":[60,100,120],"weights":[10,20,30]}
Output: 240
Take the 10 and 20 weight items whole (160) plus two-thirds of the 30-weight item (80).

Example 2

Input: {"W":25,"values":[60,100],"weights":[10,20]}
Output: 135
The denser item fills 10 units for 60; the remaining 15 units take three-quarters of the second item for 75 more.

Solve this in your browser →

Also on LeetCode ↗