Problem Statement
leetcode problem link
Brute Force approach [Accepted]
class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key=lambda x: -x[1])
curr_boxes = 0
res = 0
for num_of_boxes, unit in boxTypes:
if truckSize - num_of_boxes <= 0:
res += (unit * truckSize)
break
truckSize -= num_of_boxes
res += (unit * num_of_boxes)
return res
Editorial
Greedy Approach
class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key=lambda x: -x[1])
unitCount = 0
for boxType in boxTypes:
boxCount = min(truckSize, boxType[0])
unitCount += boxCount * boxType[1]
truckSize -= boxCount
if truckSize == 0:
break
return unitCount