[LeetCode] Maximum Units on a Truck

1710. Maximum Units on a Truck

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {
sort(begin(boxTypes), end(boxTypes), [](auto a, auto b) {
return a[1] < b[1];
});
int res = 0;
while(truckSize and !boxTypes.empty()) {
int cut = min(boxTypes.back()[0], truckSize);
truckSize -= cut;
res += cut * boxTypes.back()[1];
boxTypes.pop_back();
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/01/PS/LeetCode/maximum-units-on-a-truck/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.