Leetcode Problem 2548. Maximum Price to Fill a Bag
2548. Maximum Price to Fill a Bag
Leetcode Solutions
Greedy Approach with Sorting by Price-to-Weight Ratio
Define a lambda function to calculate the price-to-weight ratio for each item.
Sort the items array in descending order based on the price-to-weight ratio using the defined lambda function.
Initialize a variable to keep track of the total price.
Iterate through the sorted items array.
a. Determine the amount of the current item to take based on the remaining capacity.
b. Update the total price by adding the value of the taken amount of the current item.
c. Decrease the capacity by the weight of the taken amount.
If the capacity is not fully utilized after going through all items, return -1.
Otherwise, return the total price.
Using Priority Queue to Select Items with Highest Price-to-Weight Ratio