Skip to content

Commit d34be60

Browse files
authored
Create maximum-units-on-a-truck.cpp
1 parent 4cdf577 commit d34be60

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

C++/maximum-units-on-a-truck.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Time: O(nlogn)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {
7+
sort(begin(boxTypes), end(boxTypes),
8+
[](const auto& a, const auto& b) {
9+
return a[1] > b[1];
10+
});
11+
int result = 0;
12+
for (const auto& boxType : boxTypes) {
13+
if (truckSize > boxType[0]) {
14+
truckSize -= boxType[0];
15+
result += boxType[0] * boxType[1];
16+
} else {
17+
result += truckSize * boxType[1];
18+
break;
19+
}
20+
}
21+
return result;
22+
}
23+
};

0 commit comments

Comments
 (0)