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) =
3truckSize (int) =
4Returns (int)
8Example 2
Input
boxTypes (int[][]) =
[[5,10],[2,5],[4,7],[3,9]]size (int) =
4truckSize (int) =
10Returns (int)
91Example 3
Input
boxTypes (int[][]) =
[[1,3]]size (int) =
1truckSize (int) =
1Returns (int)
3Always 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 totalUnitsReady to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run