LeetCode 1710: Maximum Units on a Truck

ArrayGreedySorting

Problem Description

Explanation

To solve this problem, we need to maximize the total number of units that can be put on the truck within the given constraints. We can achieve this by sorting the boxTypes array based on the number of units per box in descending order. Then, we iterate through the sorted array and add as many boxes as possible to the truck until we reach the maximum truck size.

Algorithm:

  1. Sort the boxTypes array in descending order based on the number of units per box.
  2. Initialize a variable totalUnits to keep track of the total units loaded on the truck.
  3. Iterate through the sorted boxTypes array:
    • If the number of boxes of the current type is less than or equal to the remaining space on the truck, add all the boxes of that type to the truck and update totalUnits.
    • Otherwise, add only the remaining space of the truck with boxes of the current type and update totalUnits.
  4. Return totalUnits as the result.

The time complexity of this algorithm is O(n log n) due to sorting, where n is the number of box types. The space complexity is O(1) as we are using only a constant amount of extra space.

Solutions

import java.util.Arrays;

class Solution {
    public int maximumUnits(int[][] boxTypes, int truckSize) {
        Arrays.sort(boxTypes, (a, b) -> b[1] - a[1]);
        int totalUnits = 0;

        for (int[] box : boxTypes) {
            if (box[0] <= truckSize) {
                totalUnits += box[0] * box[1];
                truckSize -= box[0];
            } else {
                totalUnits += truckSize * box[1];
                break;
            }
        }
        return totalUnits;
    }
}

Loading editor...