# 1710. Maximum Units on a Truck

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MiLgIREZNt8MeKTZ2NC%2F-MiLh--NaXMiK7l4-ZxC%2Fimage.png?alt=media\&token=06aa3d15-bfe1-44a2-a660-b2b29cbf1b85)

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MiLgIREZNt8MeKTZ2NC%2F-MiLh228tABrif9OCs1K%2Fimage.png?alt=media\&token=f1a017a1-0b64-44fd-8cfa-b0f7eee39290)

## Greedy

pick larger unit first, so **sort by  numberOfUnitsPerBoxi desc**

**ticky part is use left box number to gen the result (not like 背包問題, 只有一個包, 這裡有多個紙箱可以用, 所以可以用 貪心）**

time: O(nlogn)

space: O(1)

```java
class Solution {
    public int maximumUnits(int[][] boxTypes, int truckSize) {
        Arrays.sort(boxTypes, (a, b) -> b[1] - a[1]); // sort by unit desc, use unit bigger one
        int res = 0;
        
        for (int boxType[] : boxTypes) {
            int boxNum = Math.min(truckSize, boxType[0]); // use < truckSize's box number
            res += boxNum * boxType[1];
            truckSize -= boxNum;
            
            if (truckSize == 0) {
                return res;
            }
        }
        return res;
    }
}
/*
[[5,10],[3,9], [4,7], [2,5]]

10 , 5 use 5
5*10 = 50. 10-5 = 5

5, 3 use 3
27  3*9, 5-3 = 2

2 4 use 2
14    2*7     2, 4 = 2

= 91


boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]

maximum number of boxes: truckSize

You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize.

maximum total number of units 

1 + 2 + 1 => weight


5*10 50

3*9 27






*/
```
