< Back





1710. Maximum Units on a Truck

Regular greedy problem, we've got a truck that can take truckSize boxes. We've got boxes described
by the number we have and the units contained within each. To solve this greedily, we sort the input
based on number of units. We then iterate through the input, selecting the highest number of boxes
we can add to the truck (either truckSize number of boxes or the boxes available for this
iteration). We add the number of units to our running total, and decrement the truckSize by the
number of boxes we just added. If there's no more space, we terminate.

The solution is as follows:


  class Solution:
      def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
          boxTypes.sort(key=lambda x: x[1], reverse=True)
          ans = 0

          for boxes, units in boxTypes:
              select = min(truckSize, boxes)
              ans += units * select
              truckSize -= select

              if not truckSize:
                  break

          return ans


_ Time Complexity:

  O(n log(n)) - We have to sort the input.

_ Space Complexity:

  O(1) - We use constant space.