Problem statement

https://leetcode.com/problems/maximum-units-on-a-truck/

Solution

We have only limit for number of boxes, not for their size, so what we need to choose boxes with biggest sizes. So, let us sort them by sizes, starting from big and then just iterate and try to put group of box in our truck. Each time we check if we can do it and if we have less space than needed, we put not all group, but such number so truck is full and then break.

Complexity

Time is just O(n log n) to sort data and space is O(n).

Code

class Solution:
    def maximumUnits(self, boxTypes, truckSize):
        ans = 0
        for box_num, units in sorted(boxTypes, key = lambda x:-x[1]):
            if not truckSize: break
            ans += min(box_num, truckSize) * units
            truckSize -= min(box_num, truckSize)

        return ans