# 1710. Maximum Units on a Truck

![](/files/-MiLh--NaXMiK7l4-ZxC)

![](/files/-MiLh228tABrif9OCs1K)

## 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






*/
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/greedy/untitled-2.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
