#1710

Maximum Units on a Truck

Easy
ArrayGreedySortingGreedySorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

The optimal solution leverages a greedy approach by sorting the box types based on the units per box in descending order. This ensures that we always take the boxes that provide the most units first, maximizing the total units on the truck.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the boxTypes array by numberOfUnitsPerBox in descending order.
  2. 2Step 2: Initialize totalUnits to 0 and iterate through the sorted boxTypes.
  3. 3Step 3: For each box type, check if the truckSize can accommodate the number of boxes available. If yes, take all boxes; otherwise, take as many as the truck can hold.
solution.py11 lines
1# Full working Python code
2def maxUnits(boxTypes, truckSize):
3    boxTypes.sort(key=lambda x: x[1], reverse=True)
4    total_units = 0
5    for boxes, units in boxTypes:
6        if truckSize <= 0:
7            break
8        boxes_to_take = min(boxes, truckSize)
9        total_units += boxes_to_take * units
10        truckSize -= boxes_to_take
11    return total_units

Complexity note: The sorting step dominates the time complexity, making it O(n log n). The subsequent iteration through the box types is O(n).

  • 1Always prioritize boxes with higher units per box.
  • 2Sorting helps in efficiently selecting the best boxes.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.