1710. Maximum Units on a Truck

1710. Maximum Units on a Truck

Question

You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxes<sub>i</sub>, numberOfUnitsPerBox<sub>i</sub>]:

  • numberOfBoxes<sub>i</sub> is the number of boxes of type i.
  • numberOfUnitsPerBox<sub>i</sub> is the number of units in each box of the type i.

You are also given an integer truckSize, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize.

Return the maximum total number of units that can be put on the truck.

Solution

根据每个箱子可以装最多单元从大到小排序。
遍历数组,如果truckSize还有剩余,则将res增加容量乘以箱子数量。
然后将truckSize减少箱子数量个。

最后返回res即可。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int maximumUnits(int[][] boxTypes, int truckSize) {
int res = 0;
Arrays.sort(boxTypes, (a,b) -> b[1] - a[1]);
for(int i = 0; i < boxTypes.length; i++){
int numberOfBoxes = boxTypes[i][0];
int numberOfUnitesPerBox = boxTypes[i][1];

if(truckSize <= numberOfBoxes){
res += numberOfUnitesPerBox * truckSize;
break;
}
else{
truckSize -= numberOfBoxes;
res += numberOfBoxes * numberOfUnitesPerBox;
}
}
return res;
}
}
Author

Xander

Posted on

2022-07-01

Updated on

2022-07-01

Licensed under

Comments