You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes
, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]
:
numberOfBoxesi
is the number of boxes of typei
.numberOfUnitsPerBoxi
is the number of units in each box of the typei
.
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.
Example 1:
Input: boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4 Output: 8 Explanation: There are: - 1 box of the first type that contains 3 units. - 2 boxes of the second type that contain 2 units each. - 3 boxes of the third type that contain 1 unit each. You can take all the boxes of the first and second types, and one box of the third type. The total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8.
Example 2:
Input: boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10 Output: 91
Constraints:
1 <= boxTypes.length <= 1000
1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000
1 <= truckSize <= 106
给了truck里能放的box数量,给了每个box里能放多少units和box的个数,求这个truck最多能放多少units。那就很无脑就把最大的box往上放就行了。唯一的难点就是写int[][]的compare方法,三种写法,prefer第三种。
Arrays.sort(boxTypes, (a, b) -> {
return b[1] - a[1];
});
Arrays.sort(boxTypes, (a, b) -> b[1] - a[1]});
Arrays.sort(boxTypes, (a, b) -> Integer.compare(a[1], b[1]));
代码:
class Solution {
public int maximumUnits(int[][] boxTypes, int truckSize) {
Arrays.sort(boxTypes, (a, b) -> Integer.compare(a[1], b[1]));
int result = 0;
int remainingBox = truckSize;
for (int i = 0; i < boxTypes.length; i++) {
int numBox = Math.min(remainingBox, boxTypes[i][0]);
remainingBox -= numBox;
result += boxTypes[i][1] * numBox;
if (remainingBox == 0) {
break;
}
}
return result;
}
}
还有人提到如果用counting sort可以达到O(n)的效果,因为题目给出了说每个box里最多只有1000个unit。counting sort的主要思想就是用一个size为n的数组来存每个数字出现了多少次。
counting sort这里有两个坑:
1. 数组长度为n+1,因为没有用到index 0,但是用了index n,所以虽然也是1000个元素但是需要1001
2. 可能会有重复的boxType[i][1]出现,就是可能会有两个pair,分别表示有1个unit=2的box,和2个unit=2的box,所以一共是3个unit=2的box。所以最开始assign bucket的时候不能用=只能用+=
class Solution {
public int maximumUnits(int[][] boxTypes, int truckSize) {
int[] buckets = new int[1001];
for (int[] box : boxTypes) {
buckets[box[1]] += box[0];
}
int result = 0;
int remainingBox = truckSize;
for (int i = buckets.length - 1; i > 0; i--) {
if (buckets[i] != 0) {
int numBox = Math.min(remainingBox, buckets[i]);
remainingBox -= numBox;
result += i * numBox;
if (remainingBox == 0) {
break;
}
}
}
return result;
}
}