题目链接
题目描述
注意
- 卡车上能够装载的箱子的数量是不变的
解答思路
- 根据每个箱子可以装载的单元数量对箱子集合进行排序,再从大到小依次将相应数量的箱子添加到卡车中,最终得到的单元数量总数就是卡车可以装载单元的最大总数
代码
方法一:
class Solution {
public int maximumUnits(int[][] boxTypes, int truckSize) {
Arrays.sort(boxTypes, Comparator.comparingInt(o -> o[1]));
int res = 0;
for(int i = boxTypes.length - 1; i >= 0; i--) {
if(truckSize > boxTypes[i][0]) {
res += boxTypes[i][0] * boxTypes[i][1];
truckSize -= boxTypes[i][0];
} else {
res += truckSize * boxTypes[i][1];
break;
}
}
return res;
}
}
关键点
- 对元素为数组的集合想要以某个属性进行排序的方法
- 贪心算法