Problem : https://leetcode.com/problems/maximum-units-on-a-truck/
Greedily take the largest boxes first. Use heap to avoid sort all boxes.
class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
heap = [(-m, -n) for n, m in boxTypes]
heapq.heapify(heap)
result = 0
while truckSize and heap:
m, n = heapq.heappop(heap)
m, n = -m, -n
taken = min(truckSize, n)
result += m * taken
truckSize -= taken
return result
No comments:
Post a Comment