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

  1. Define a lambda function to calculate the price-to-weight ratio for each item.
  2. Sort the items array in descending order based on the price-to-weight ratio using the defined lambda function.
  3. Initialize a variable to keep track of the total price.
  4. 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.
  5. If the capacity is not fully utilized after going through all items, return -1.
  6. Otherwise, return the total price.
UML Thumbnail

Using Priority Queue to Select Items with Highest Price-to-Weight Ratio

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...