Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Approach (Greedy / Fractional Knapsack):
- To maximize total units/value with a limited capacity `n`, always pick from the item
- that gives the highest units per box (value density) first. So we sort `arr` in
- descending order of `unitsPerBox`, then take as many boxes as possible from each item.
- If the remaining capacity is smaller than available boxes, we take only that fraction
- and stop. This guarantees the maximum possible total units.
- """
- class Solution:
- def maximumUnits(self, arr: List[List[int]], n: int) -> int:
- arr.sort(key=lambda x: x[1],reverse=True)
- ans=0
- i=0
- while i<len(arr) and n>0:
- if n>arr[i][0]:
- ans+=(arr[i][0]*arr[i][1])
- n-= arr[i][0]
- i+=1
- else:
- ans+=(n*arr[i][1])
- n=0
- i+=1
- return ans
Advertisement
Add Comment
Please, Sign In to add comment