LeetCode 筆記 - 1710. Maximum Units on a Truck

題目在此 1710. Maximum Units on a Truck

給定每種盒子裡面有幾個單位,還有卡車可以裝幾個盒子,請給出一車次最多可以載多少個單位

解題思維

就簡單按照盒子裡有幾個單位排序,大的排前面

就慢慢計算到卡車裝滿為止

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
# truck size: the number of boxes that can be put on the truck

result = 0

boxTypes.sort(key=lambda x: -x[1])

result = 0
for boxType in boxTypes:

boxes = (truckSize if truckSize <= boxType[0] else boxType[0])

truckSize -= boxes
result += boxes * boxType[1]

if truckSize == 0:
break

return result

也許你也會想看看