LeetCode 1710. Maximum Units on a Truck
考点 | 难度 |
---|---|
Sorting | Easy |
题目
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 type i.
numberOfUnitsPerBoxi
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.
思路
先对box的priority排序,先满足所有priority高的box直到装不下,返回总unit数。
答案
public int maximumUnits(int[][] B, int T) {
Arrays.sort(B, (a,b) -> b[1] - a[1]);
int ans = 0;
for (int[] b : B) {
// exhaust all boxes of the type or exhuast T
int count = Math.min(b[0], T);
// add number of units to answer
ans += count * b[1];
// find number of boxes truck can hold
T -= count;
// if truck is full, return
if (T == 0) return ans;
}
return ans;
}