「每日LeetCode」2021年3月29日

本文最后更新于:2023年3月19日 晚上

Lt1710. 卡车上的最大单元数

1710. 卡车上的最大单元数

请你将一些箱子装在 一辆卡车 上。给你一个二维数组 boxTypes ,其中 boxTypes[i] = [numberOfBoxes, numberOfUnitsPerBox]

  • numberOfBoxes 是类型 i 的箱子的数量。
  • numberOfUnitsPerBox是类型 i 每个箱子可以装载的单元数量。

整数 truckSize 表示卡车上可以装载 箱子最大数量 。只要箱子数量不超过 truckSize ,你就可以选择任意箱子装到卡车上。
返回卡车可以装载 单元最大 总数
示例 1:

1
2
3
4
5
6
7
8
输入:boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4
输出:8
解释:箱子的情况如下:
- 1 个第一类的箱子,里面含 3 个单元。
- 2 个第二类的箱子,每个里面含 2 个单元。
- 3 个第三类的箱子,每个里面含 1 个单元。
可以选择第一类和第二类的所有箱子,以及第三类的一个箱子。
单元总数 = (1 * 3) + (2 * 2) + (1 * 1) = 8

示例 2:

1
2
输入:boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10
输出:91

提示:

  • 1 <= boxTypes.length <= 1000
  • 1 <= numberOfBoxes, numberOfUnitsPerBox <= 1000
  • 1 <= truckSize <= 10

思路

贪心,先优先取 size 大的,按 size 降序排序。一直取到个数上线,求和即可。

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* @param {number[][]} boxTypes
* @param {number} truckSize
* @return {number}
*/
var maximumUnits = function (boxTypes, truckSize) {
let res = 0,
rest = truckSize;
boxTypes.sort((a, b) => b[1] - a[1]);
while (rest > 0 && boxTypes.length) {
const maxBox = boxTypes[0];
const [num, size] = maxBox;
const countNum = rest >= num ? num : rest;
rest -= countNum;
res += countNum * size;
boxTypes.shift();
}
return res;
};