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 truckSize boxes, and every box takes one place, whatever it holds. The boxes come in types: boxTypes[i] = [numberOfBoxes, unitsPerBox] means there are numberOfBoxes boxes of type i, each holding unitsPerBox units. No box holds more than 1000 units. Return the largest total number of units the truck can carry.

Example 1
Input: boxTypes = [[1, 3], [2, 2], [3, 1]], truckSize = 4
Output: 8
Explanation: 1 box of 3 units, 2 boxes of 2, and 1 box of 1: 3 + 4 + 1.
Example 2
Input: boxTypes = [[5, 10], [2, 5], [4, 7], [3, 9]], truckSize = 10
Output: 91
Solution

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.

Example 2: the truck has 10 places. It takes 5 boxes of 10 units (total 50), 3 boxes of 9 (total 77) and 2 boxes of 7 (total 91). Two boxes of 7 and two boxes of 5 are left behind.

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 works in these steps:

  1. First, sort boxTypes with Arrays.sort. Its second argument, a comparator, tells the sort which of two rows a and b goes first. Here it returns Integer.compare(b[1], a[1]), which compares units per box with b before a, so the most units per box come first. The sort reorders the caller's array in place.
  2. Set a running total, units, to 0, and walk the sorted types with a for loop, one row type at a time.
  3. For each type, compute take as Math.min(type[0], truckSize): all of its boxes, or the places still free. Add take * type[1] to units and subtract take from truckSize, which from here on counts the places still free.
  4. When truckSize reaches 0, the truck is full and break leaves the loop. Either way, the method returns units.

The main method runs both examples, a truck with room to spare, a single type that must be split, and two types with the same units per box.

Java
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:

Output
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]] with room for 100: the loop loads all three boxes, 3 + 2 + 2 units, and ends without the truck ever filling up.

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 Arrays.sort on an array of int[] rows may need temporary room for up to half the rows, while the loop itself keeps only units and 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 Partition Equal Subset Sum.