Maximum Units on a Truck
Load a truck with as many units as possible by giving each place to the fullest box left.
A truck has room for at most truckSizeboxTypes[i] = [numberOfBoxes, unitsPerBox]numberOfBoxesiunitsPerBox
Example 1
Output: 8
Explanation: 1 box of 3 units, 2 boxes of 2, and 1 box of 1: 3 + 4 + 1.
Example 2
Output: 91
The Idea
Picture a truck with ten empty places in the back and fourteen boxes waiting beside it. That is Example 2: five boxes hold 10 units each, two hold 5, four hold 7 and three hold 9. The boxes are all the same size, so any ten of them fit. Which ten should go in?
Suppose one place gets a box of 5. A box of 10 would take exactly the same place and bring 5 more units. Since every box costs one place and nothing else, a place is always better used by a box with more units. That raises a question: if we keep loading the fullest box that is still on the ground, do we end up with the best load?
Look at the picture below. The first five places go to the five boxes of 10, for 50 units. The next three go to the boxes of 9, and the total reaches 77. Two places are left, and boxes of 7 come next, so two of the four boxes of 7 go in, for a total of 91.
Now look at the row labelled "left behind": two boxes of 7 and two boxes of 5. Every box on the truck holds at least 7 units, and no box on the ground holds more than 7. Swapping a box on the truck for one on the ground never adds units, so no other choice of ten boxes beats 91.
Filling each place with the box that looks best right now, without planning ahead for the places still empty, is called a greedy choice. Here it is safe because the boxes differ only in what they hold, never in how much room they take.
Solution Approach
Turning that idea into code means settling two things: the order in which to visit the box types, and how many boxes to take from each. The 1000-unit limit also allows an optional faster sort.
Ordering the box types
How do we find the fullest box left, place after place? The simple way is to look through all the types for every place. With ten places and four types, that is forty looks, and the work grows with the number of places times the number of types.
Sorting the types once, by units per box with the largest first, removes the search. The fullest boxes are then at the front, and loading becomes a walk from the first type to the last. Example 2 sorted reads [5, 10], [3, 9], [4, 7], [2, 5], the same order the boxes appear in the picture, the truck first and then the row labelled "left behind".
The sort must use units per box, not the total units of a type. In Example 2 the four boxes of 7 hold 28 units together, more than the 27 in the three boxes of 9. A version that sorts by those totals loads the 7s first, runs out of room after one box of 9, and returns 87 instead of 91.
How many boxes to take from each type
How many boxes of the current type go in? All of them if they fit, otherwise only as many as there are places left. So the count is the smaller of the type's box count and the places left. Only the type being loaded when the truck fills up gets split, as the 7s were in the picture.
Once no places are left, the remaining types cannot add anything, so the walk can stop. If the truck has more places than there are boxes, the walk simply reaches the end with every box loaded.
Sorting by counting (optional)
Since no box holds more than 1000 units, the sort can be replaced by counting. An array with one entry for each unit value from 0 to 1000 records how many boxes hold that many units, filled in one pass over the types. Reading it from 1000 down gives the boxes fullest first, without comparing any two types.
Java Solution
The method maximumUnits
- First, sort
withboxTypes . Its second argument, a comparator, tells the sort which of two rowsArrays.sort anda goes first. Here it returnsb , which compares units per box withInteger.compare(b[1], a[1]) beforeb , so the most units per box come first. The sort reorders the caller's array in place.a - Set a running total,
, to 0, and walk the sorted types with aunits loop, one rowfor at a time.type - For each type, compute
astake : all of its boxes, or the places still free. AddMath.min(type[0], truckSize) totake * type[1] and subtractunits fromtake , which from here on counts the places still free.truckSize - When
reaches 0, the truck is full andtruckSize leaves the loop. Either way, the method returnsbreak .units
The main
import java.util.Arrays;
public class MaximumUnitsOnATruck {
public static int maximumUnits(int[][] boxTypes, int truckSize) {
Arrays.sort(boxTypes, (a, b) -> Integer.compare(b[1], a[1])); // most units per box first
int units = 0;
for (int[] type : boxTypes) {
int take = Math.min(type[0], truckSize); // all of this type, or what still fits
units += take * type[1];
truckSize -= take;
if (truckSize == 0) {
break; // the truck is full
}
}
return units;
}
public static void main(String[] args) {
System.out.println(maximumUnits(new int[][] {{1, 3}, {2, 2}, {3, 1}}, 4));
System.out.println(maximumUnits(new int[][] {{5, 10}, {2, 5}, {4, 7}, {3, 9}}, 10));
System.out.println(maximumUnits(new int[][] {{1, 3}, {2, 2}}, 100)); // room to spare
System.out.println(maximumUnits(new int[][] {{5, 10}}, 3)); // one type, split
System.out.println(maximumUnits(new int[][] {{2, 4}, {3, 4}, {1, 1}}, 5)); // equal units
}
}
Running it prints:
8
91
7
30
20
The 8 is Example 1: the box of 3, both boxes of 2 and one of the three boxes of 1. The 91 below it is the load in the picture. The 7 comes from [[1, 3], [2, 2]]
The 30 is the split case, three of the five boxes of 10. The last line, 20, comes from two types that both hold 4 units per box. Five places take all five of their boxes, so the order between equal types makes no difference to the total.
Complexity
The work is one sort of the box types followed by one walk over them.
- Time: O(n log n), because sorting the n box types costs the most, while the loading loop looks at each type at most once and adds only O(n). With the optional counting array, the whole method takes O(n + 1000).
- Space: O(n) in the worst case, because
on an array ofArrays.sort rows may need temporary room for up to half the rows, while the loop itself keeps onlyint[] andunits .take
When boxes differ in size as well as in units, filling each place with the fullest box can fail. A table of best results for smaller trucks is needed instead, as in