imashutosh51

Maximum Units on a Truck

Feb 7th, 2026
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.90 KB | None | 0 0
  1. """
  2. Approach (Greedy / Fractional Knapsack):
  3. To maximize total units/value with a limited capacity `n`, always pick from the item
  4. that gives the highest units per box (value density) first. So we sort `arr` in
  5. descending order of `unitsPerBox`, then take as many boxes as possible from each item.
  6. If the remaining capacity is smaller than available boxes, we take only that fraction
  7. and stop. This guarantees the maximum possible total units.
  8. """
  9.  
  10.  
  11. class Solution:
  12.     def maximumUnits(self, arr: List[List[int]], n: int) -> int:
  13.         arr.sort(key=lambda x: x[1],reverse=True)
  14.         ans=0
  15.         i=0
  16.         while i<len(arr) and n>0:
  17.             if n>arr[i][0]:
  18.                 ans+=(arr[i][0]*arr[i][1])
  19.                 n-= arr[i][0]
  20.                 i+=1
  21.             else:
  22.                 ans+=(n*arr[i][1])
  23.                 n=0
  24.                 i+=1
  25.         return ans
  26.        
  27.  
  28.        
Advertisement
Add Comment
Please, Sign In to add comment