Leetcode #2548: Maximum Price to Fill a Bag
In this guide, we solve Leetcode #2548 Maximum Price to Fill a Bag in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Greedy, Array, Sorting
Intuition
A locally optimal choice leads to a globally optimal result for this structure.
That means we can commit to decisions as we scan without backtracking.
Approach
Sort or preprocess if needed, then repeatedly take the best available local choice.
Maintain the minimal state necessary to validate the greedy decision.
Steps:
- Sort or preprocess as needed.
- Iterate and pick the best local option.
- Track the current solution.
Example
Input: items = [[50,1],[10,8]], capacity = 5
Output: 55.00000
Explanation:
We divide the 2nd item into two parts with part1 = 0.5 and part2 = 0.5.
The price and weight of the 1st item are 5, 4. And similarly, the price and the weight of the 2nd 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 1st element with a price of 50 and the 2nd element with a price of 5.
It can be proved that 55.0 is the maximum total price that we can achieve.
Python Solution
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
Complexity
The time complexity is , and the space complexity is , where is the number of items. The space complexity is , where is the number of items.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.