Leetcode 1710. 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] = [numberOfBoxes_i, numberOfUnitsPerBox_i]
:
numberOfBoxes_i
is the number of boxes of type i
.numberOfUnitsPerBox_i
is the number of units in each box of the type i
.You are also given an integer truckSize
, which represents the maximum number of boxes that can be put on the truck.
You need to return the maximum total number of units that can be put on the truck.
Input: boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4
Output: 8
Explanation: There are:
- 1 box of the first type that contains 3 units.
- 2 boxes of the second type that contain 2 units each.
- 3 boxes of the third type that contain 1 unit each.
You can take all the boxes of the first and second types, and one box of the third type.
The total number of units will be = (1*3) + (2*2) + (1*1) = 3 + 4 + 1 = 8.
boxTypes
?
boxTypes
will fit in memory.numberOfBoxes_i
, numberOfUnitsPerBox_i
, and truckSize
?
boxTypes
be empty or can truckSize
be zero?
boxTypes
by the number of units per box in descending order.boxTypes
:
Let’s implement this approach in C++:
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {
// Sort the boxTypes based on the second element in descending order
sort(boxTypes.begin(), boxTypes.end(), [](const vector<int>& a, const vector<int>& b) {
return a[1] > b[1];
});
int maxUnits = 0;
for (const auto& box : boxTypes) {
int numBoxes = box[0];
int unitsPerBox = box[1];
if (truckSize >= numBoxes) {
// If all boxes of this type can be loaded
maxUnits += numBoxes * unitsPerBox;
truckSize -= numBoxes;
} else {
// If only part of the boxes can be loaded
maxUnits += truckSize * unitsPerBox;
break; // Truck is now full
}
}
return maxUnits;
}
};
n
is the number of box types.boxTypes
Array: O(n)Thus, the overall time complexity is O(n log n) due to the sorting operation. The space complexity is O(1) if we do not account for the input storage.
boxTypes
array by units per box in descending order ensures that we maximize the units loaded per space on the truck.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?