Ctrl K

Fill the Sack to the Brim

Medium
A merchant fills a sack with spices. Spice i is the pair goods[i] = [price, weight]: its whole batch weighs weight kg and costs price. Any batch can be split in any proportion, and a portion of x kg costs price · x / weight. The sack holds exactly capacity kg and must be filled to the brim. Return the highest possible value of its contents, or -1 if it cannot be filled completely. Answers within 10⁻⁵ of the true value are accepted.
Example 1
goods=[[12, 3], [10, 5], [3, 3]], capacity=6 → 18.0

The first spice is the priciest per kilogram (4 per kg), so take all 3 kg of it for 12. Next comes the second (2 per kg): 3 of its 5 kg add 6. Total 18.

Example 2
goods=[[7, 2], [5, 1]], capacity=4 → -1

There are only 3 kg of goods, so the 4 kg sack cannot be filled: the answer is -1.

Example 3
goods=[[9, 4]], capacity=1 → 2.25
Constraints
  • 1 ≤ len(goods) ≤ 10⁵
  • goods[i] = [price, weight], 1 ≤ price, weight ≤ 10⁴
  • 1 ≤ capacity ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBiggest Number From Pieces MediumStudios for Recording Sessions MediumLow, High, Low MediumStrictly Low, High, Low MediumFewest Meetings to Cancel Medium
loading Python…
Input
goods=[[12, 3], [10, 5], [3, 3]], capacity=6
Expected
18.0

Run checks the first 3 tests in your browser. Submit checks all 114 tests on the server, hidden ones included.