Start learning free

LESSON 549 OF 677 · GREEDY

Maximum Units on a Truck

Practice Greedy, O(n log n)

You get an array boxTypes and an integer truckSize. Each pair in boxTypes is one kind of box:

  • boxTypes[i][0] is how many boxes of kind i you have.
  • boxTypes[i][1] is how many units each of those boxes holds.

Return the largest total number of units you can load onto one truck.

The truck carries at most truckSize boxes. You can pick any boxes you like.

Example 1

Input: boxTypes = [[2,5],[4,8],[3,2]], truckSize = 5
Output: 37
Explanation: Load the 4 boxes of 8 units.
Then load 1 box of 5 units.
That is 5 boxes, as many as the truck takes.
In total, 4 * 8 + 1 * 5 = 37.

Example 2

Input: boxTypes = [[3,6],[1,9]], truckSize = 10
Output: 27
Explanation: There are only 4 boxes, so they all fit.
In total, 3 * 6 + 1 * 9 = 27.

Example 3

Input: boxTypes = [[6,1],[2,3],[1,3]], truckSize = 2
Output: 6
Explanation: Load two boxes of 3 units each.
They can come from either of the last two kinds.
In total, 3 + 3 = 6.

Constraints

  • 1 to 1,000 kinds of boxes.
  • Both numbers of every pair are from 1 to 1,000.
  • truckSize is from 1 to 1,000,000.
STEP 1 OF 7
    Ctrl + Enter to check