Maximum Units on a Truck LeetCode solution in C++

1
class Solution {
2
public:
3
static bool myfunction(vector<int> &a, vector<int> &b) {
4
return a[1] > b[1];
5
}
6
int maximumUnits(vector<vector<int>> &boxTypes, int truckSize) {
7
// custom sort (in increasing order of numberOfUnitsPerBox as we have to
8
// return maximum total number of units )
9
sort(boxTypes.begin(), boxTypes.end(), myfunction);
10
// greedily pick boxes till capacity is full
11
int ans = 0;
12
for (auto box : boxTypes) {
13
int x = min(box[0], truckSize); // choose minimum boxes from available
14
// boxes and capacity left
15
ans += (x * box[1]); // adding units in ans
16
truckSize -= x; // reduce the capacity
17
if (!truckSize) break; // capacity full
18
}
19
return ans;
20
}
21
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0