Sponsored
This approach involves sorting the box types by the number of units per box in descending order. Once sorted, the boxes are loaded onto the truck with the highest units per box first, maximizing the number of units on the truck until it reaches its capacity.
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(1) extra space, as we sort in place.
1#include <vector>
2#include <algorithm>
3using namespace std;
4
5class Solution {
6public:
7 int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {
8 sort(boxTypes.begin(), boxTypes.end(), [](const vector<int>& a, const vector<int>& b) {
9 return b[1] > a[1];
10 });
11
12 int totalUnits = 0;
13 for (const auto& box : boxTypes) {
14 int boxesToTake = min(box[0], truckSize);
15 totalUnits += boxesToTake * box[1];
16 truckSize -= boxesToTake;
17 if (truckSize == 0) break;
18 }
19 return totalUnits;
20 }
21};
This C++ solution sorts the boxTypes
by units per box in descending order using a lambda function. It then iterates through sorted boxes to fill the truck with maximum units.
Instead of sorting by each unit's count, employ counting sort principles to store the total units in an array where the index represents the units per box. This could potentially be faster for large inputs with many boxes and limited unit types.
Time Complexity: O(n + M) where M = 1000 is a constant.
Space Complexity: O(M) for the counting array.
1
Python solution utilizes a counting array approach where units are prioritized by their count indices, providing quick access to maximum unit decisions.