Intermediate Level

Implement the maximumUnitsTruck method that returns the maximum units that can be loaded onto the truck.

The input contains boxTypes, where each entry is [numberOfBoxes, unitsPerBox], and truckSize, the maximum number of boxes the truck can carry.

Your task is to load boxes in a way that gives the maximum total units on the truck.

For example, with [[1,3],[2,2],[3,1]] and truck size 4, the best choice gives 8 units.

Example 1
Input:
boxTypes (int[][]) = [[1,3],[2,2],[3,1]]
size (int) = 3
truckSize (int) = 4
Return:
(int) 8
Example 2
Input:
boxTypes (int[][]) = [[5,10],[2,5],[4,7],[3,9]]
size (int) = 4
truckSize (int) = 10
Return:
(int) 91
Example 3
Input:
boxTypes (int[][]) = [[1,3]]
size (int) = 1
truckSize (int) = 1
Return:
(int) 3

Always take boxes with more units first.

Sort the box types by unitsPerBox in descending order. For each type, take as many boxes as possible without exceeding the remaining truck capacity. Add takenBoxes * unitsPerBox to the answer.

Stop when the truck becomes full or all box types have been processed.

Pseudocode:

function maximumUnitsTruck(boxTypes, size, truckSize):
    sort boxTypes by unitsPerBox descending
    totalUnits = 0
    remaining = truckSize
    for each boxType in boxTypes:
        boxes = boxType[0]
        units = boxType[1]
        take = min(boxes, remaining)
        totalUnits = totalUnits + take * units
        remaining = remaining - take
        if remaining == 0:
            break
    return totalUnits
Run your code to see the result.