请你将一些箱子装在 一辆卡车 上。给你一个二维数组 boxTypes ,其中 boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi] :
- numberOfBoxesi 是类型
i的箱子的数量。- numberOfUnitsPerBoxi 是类型
i每个箱子可以装载的单元数量。
整数 truckSize 表示卡车上可以装载 箱子 的 最大数量 。只要箱子数量不超过 truckSize ,你就可以选择任意箱子装到卡车上。 返回卡车可以装载 单元 的 最大 总数。
【输入】boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4
【输出】8
【解释】箱子的情况如下:1 个第一类的箱子,里面含 3 个单元。2 个第二类的箱子,每个里面含 2 个单元。3 个第三类的箱子,每个里面含 1 个单元。可以选择第一类和第二类的所有箱子,以及第三类的一个箱子。单元总数 = (1 * 3) + (2 * 2) + (1 * 1) = 8
【输入】boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10
【输出】91
1 <= boxTypes.length <= 10001 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 10001 <= truckSize <= 10^6根据题目要求,要获得卡车可以装载单元的最大总数。那么我们是需要执行下面两个步骤即可:
【步骤1】根据
numberOfUnitsPerBox对数组boxTypes进行排序。
【步骤2】从大到小获取boxType,并计算总装载单元数,直到满足truckSize。
其中,关于排序,我们可以采用Arrays.sort(...)方法对数组boxTypes进行排序;并且由于提示中描述了numberOfUnitsPerBox <= 1000,所以我们也可以通过创建int[1001]的数组来实现排序。具体操作如下图所示:

时间复杂度:O(n log n);其中:n是boxTypes数组的长度。
- class Solution {
- public int maximumUnits(int[][] boxTypes, int truckSize) {
- int result = 0;
- Arrays.sort(boxTypes, Comparator.comparingInt(o -> o[1]));
- for (int i = boxTypes.length - 1; i >= 0; i--) {
- if (truckSize > boxTypes[i][0]) {
- result += boxTypes[i][0] * boxTypes[i][1];
- truckSize -= boxTypes[i][0];
- } else {
- result += truckSize * boxTypes[i][1];
- return result;
- }
- }
- return result;
- }
- }

- class Solution {
- public int maximumUnits(int[][] boxTypes, int truckSize) {
- int result = 0;
- int[] type = new int[1001]; // index:箱子可以装载的单元数量 type[index]:index类型的箱子的数量
- for (int[] boxType : boxTypes) type[boxType[1]] += boxType[0];
- for (int i = type.length - 1; i >= 0; i--) {
- if (type[i] == 0) continue;
- if (truckSize > type[i]) {
- result += i * type[i];
- truckSize -= type[i];
- } else {
- result += i * truckSize;
- return result;
- }
- }
- return result;
- }
- }

今天的文章内容就这些了:
写作不易,笔者几个小时甚至数天完成的一篇文章,只愿换来您几秒钟的 点赞 & 分享 。
更多技术干货,欢迎大家关注公众号“爪哇缪斯” ~ \(^o^)/ ~ 「干货分享,每天更新」