Maximum Price to Fill a Bag - Problem
Imagine you're a master trader at a precious metals market, and you have access to various fractional items that can be divided into any portions you want! ๐ฐ
You're given a collection of items where each item has a price and weight. The fascinating twist? You can split any item into fractional parts - if you take 30% of an item, you get 30% of its price and 30% of its weight.
Your goal is to fill a bag of exactly capacity weight to achieve the maximum possible total price. Think of it like a fractional knapsack where you must use the entire capacity - no more, no less!
Key Points:
- Each item can be split:
part1 + part2 = 1.0 - Split item value:
price ร part1, weight ร part1 - You must fill the bag to exactly the given capacity
- Return
-1if impossible to fill exactly
Input & Output
example_1.py โ Basic Case
$
Input:
items = [[60,10],[100,20],[120,30]], capacity = 50
โบ
Output:
240.00000
๐ก Note:
Take all of item 1 (60 price, 10 weight) and item 2 (100 price, 20 weight). For the remaining 20 weight capacity, take 20/30 = 2/3 of item 3, giving us 2/3 * 120 = 80 price. Total: 60 + 100 + 80 = 240.
example_2.py โ Exact Fit
$
Input:
items = [[20,50],[30,60]], capacity = 110
โบ
Output:
50.00000
๐ก Note:
We can take the complete first item (20 price, 50 weight) and complete second item (30 price, 60 weight) to exactly fill capacity 110. Total price: 20 + 30 = 50.
example_3.py โ Impossible Case
$
Input:
items = [[10,20],[20,30]], capacity = 60
โบ
Output:
-1
๐ก Note:
Total weight of all items is 20 + 30 = 50, which is less than required capacity of 60. It's impossible to fill the bag exactly to capacity 60, so return -1.
Constraints
- 1 โค items.length โค 105
- items[i].length == 2
- 1 โค pricei, weighti โค 104
- 1 โค capacity โค 105
- Answers within 10-5 of actual answer will be accepted
Visualization
Tap to expand
Understanding the Visualization
1
Calculate Value Density
Determine the 'bang for buck' of each treasure by dividing value by weight
2
Sort by Density
Arrange treasures from highest to lowest value density - most profitable first
3
Greedy Selection
Take complete treasures starting with the most valuable per unit weight
4
Perfect Fit
Cut the final treasure to exactly fill the remaining capacity
Key Takeaway
๐ฏ Key Insight: The greedy approach works perfectly for fractional knapsack because we can always take the optimal fraction of the last item to exactly fill the remaining capacity, ensuring maximum value density throughout.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code