Leetcode 1710. Maximum Units on a Truck
You are assigned to put some amount of boxes onto a 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 is the maximum number of boxes that can be put on the truck. You need to maximize the total number of units that can be put on the truck.
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:
- Load 1 box of type [1,3] => 3 units.
- Load 2 boxes of type [2,2] => 4 units.
- Load 1 box of type [3,1] => 1 unit.
Total units = 3 + 4 + 1 = 8.
Input: boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10
Output: 91
1 <= boxTypes.length <= 1000
1 <= numberOfBoxes_i, numberOfUnitsPerBox_i <= 1000
1 <= truckSize <= 10^6
```Since we want to maximize the number of units, we can use a greedy algorithm:
boxTypes
based on the number of units per box in descending order.boxTypes
.The overall time complexity would be (O(n \log n)).
import java.util.Arrays;
public class Solution {
public int maximumUnits(int[][] boxTypes, int truckSize) {
// Step 1: Sort the boxTypes based on units per box in descending order
Arrays.sort(boxTypes, (a, b) -> b[1] - a[1]);
int maxUnits = 0;
// Step 2: Load the truck with boxes
for (int[] box : boxTypes) {
int numberOfBoxes = box[0];
int unitsPerBox = box[1];
if (truckSize >= numberOfBoxes) {
// If the truck can take all boxes of this type
maxUnits += numberOfBoxes * unitsPerBox;
truckSize -= numberOfBoxes;
} else {
// If the truck can only take part of the boxes of this type
maxUnits += truckSize * unitsPerBox;
break;
}
}
return maxUnits;
}
}
In this approach:
boxTypes
based on the units per box in descending order.boxTypes
to fill the truck as much as possible, focusing on the boxes with the most units first.This ensures that we maximize the number of units loaded onto 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?