Maximum Price to Fill a Bag Problem
Description
LeetCode Problem 2548.
You are given a 2D integer array items where items[i] = [price_i, weight_i] denotes the price and weight of the i^th 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
weight_i * part1and the price of the first item isprice_i * part1. - Similarly, the weight of the second item is
weight_i * part2and the price of the second item isprice_i * 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.
Example 1:
Input: items = [[50,1],[10,8]], capacity = 5
Output: 55.00000
Explanation:
We divide the 2^nd item into two parts with part1 = 0.5 and part2 = 0.5.
The price and weight of the 1^st item are 5, 4. And similarly, the price and the weight of the 2^nd item are 5, 4.
The array items after operation becomes [[50,1],[5,4],[5,4]].
To fill a bag with capacity 5 we take the 1^st element with a price of 50 and the 2^nd element with a price of 5.
It can be proved that 55.0 is the maximum total price that we can achieve.
Example 2:
Input: items = [[100,30]], capacity = 50
Output: -1.00000
Explanation: It is impossible to fill a bag with the given item.
Constraints:
1 <= items.length <= 10^5items[i].length == 21 <= price_i, weight_i <= 10^41 <= capacity <= 10^9
Solution
Approach: Greedy + Sorting
Items can be split, so the best bag takes the items with the highest price per unit of weight first. Sort by that ratio in descending order (comparing p1 * w2 with p2 * w1 avoids division). Then take items in order: for each, take min(weight, remaining capacity) and add the matching share of its price. If capacity is left over at the end, the items cannot fill the bag and the answer is -1.
Complexity: O(n log n) time and O(1) extra space beyond the sort.
class Solution:
def maxPrice(self, items: List[List[int]], capacity: int) -> float:
ans = 0
for p, w in sorted(items, key=lambda x: x[1] / x[0]):
v = min(w, capacity)
ans += v / w * p
capacity -= v
return -1 if capacity else ans