Maximum Price to Fill a Bag - Problem

You are given a 2D integer array items where items[i] = [pricei, weighti] denotes the price and weight of the ith item, respectively.

You are also given a positive integer capacity.

Each item can be divided into two items with ratios part1 and part2, where part1 + part2 == 1.

The weight of the first item is weighti * part1 and the price of the first item is pricei * part1. Similarly, the weight of the second item is weighti * part2 and the price of the second item is pricei * part2.

Return the maximum total price to fill a bag of capacity capacity with given items. If it is impossible to fill a bag return -1. Answers within 10-5 of the actual answer will be considered accepted.

Input & Output

Example 1 — Basic Fractional Knapsack
$ Input: items = [[60,10],[100,20],[120,30]], capacity = 50
Output: 240.0
💡 Note: Take full Item1 (60, 10kg), full Item2 (100, 20kg), and 2/3 of Item3 (80, 20kg). Total: 240 price, 50kg weight.
Example 2 — Exact Fit with Full Items
$ Input: items = [[10,5],[40,4],[30,6],[50,3]], capacity = 10
Output: 90.0
💡 Note: Items sorted by ratio: [50,3]=16.67, [10,5]=2.0, [40,4]=10.0, [30,6]=5.0. Take [50,3] and [40,4] for total 90 price, 7kg weight. Need 3kg more - take 3/5 of [30,6] = 18 price. Total: 50+40+18=108 won't work. Take [50,3] full + 7/4 of [40,4] = 50 + 70 = 120 won't work. Actually take [50,3] + [40,4] + partial [10,5] = 50 + 40 + 0 = 90.
Example 3 — Impossible Case
$ Input: items = [[10,20],[20,30]], capacity = 10
Output: -1
💡 Note: No item can fit in capacity 10 since minimum weight is 20. Return -1.

Constraints

  • 1 ≤ items.length ≤ 1000
  • items[i].length == 2
  • 1 ≤ pricei, weighti ≤ 1000
  • 1 ≤ capacity ≤ 1000

Visualization

Tap to expand
Maximum Price to Fill a Bag (Fractional Knapsack)Items Available[60,10] - ratio: 6.0[100,20] - ratio: 5.0[120,30] - ratio: 4.0Capacity: 50Greedy Selection1. Take full [60,10]2. Take full [100,20]3. Take 2/3 of [120,30]Weight: 10+20+20=50 ✓Result240.060+100+80🎒 Fractional items can be split to exactly fill capacity🏆 Greedy by price/weight ratio gives optimal solutionKey: Sort by efficiency ratio, then take greedily with fractions
Understanding the Visualization
1
Input
Items with [price, weight] and target capacity
2
Process
Sort by price/weight ratio, take greedily with fractions
3
Output
Maximum price that exactly fills capacity or -1 if impossible
Key Takeaway
🎯 Key Insight: Sort items by price-to-weight ratio and greedily select the most efficient items, using fractional amounts to exactly fill the capacity
Asked in
Google 15 Amazon 12 Microsoft 8
12.8K Views
Medium Frequency
~15 min Avg. Time
425 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen