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:
105.0
💡 Note:
Items sorted by ratio: [50,3]=16.67, [40,4]=10.0, [30,6]=5.0, [10,5]=2.0. Take [50,3] (3kg) + [40,4] (4kg) = 7kg total, 90 price so far. Need 3kg more, take 3/6 = 0.5 of [30,6] = 15 price, 3kg. Total: 50 + 40 + 15 = 105 price, 10kg weight.
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code