Sourav Dey # LeetCode Question - 1710. Maximum Units on a Truck 🚛

### 1st July 2022 | 🗓 Daily LeetCode Challenge - #1

Read more blogs from the leetcode Series →

Share the blog

## LeetCode Question - 1710. Maximum Units on a Truck 🚛

Problem-solving is a key skill set for any tech-related stuff you might be working on.

When it comes to developers it's one of the most crucial skills which is needed in almost any day-to-day code you might be writing.

So, this series of blogs is all about practicing Daily LeetCode Challenges & Problem-solving. 🚀

### Problem Statement

Maximum Units on a Truck 🚛

You are assigned to put some amount of boxes onto one truck. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`:

• `numberOfBoxes` is the number of boxes of type i.
• `numberOfUnitsPerBox` is the number of units in each box of type i. You are also given an integer `truckSize`, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`.

Return the maximum total number of units that can be put on the truck.

### Solution

Algorithm

• Sorting the array in descending order based on the no. of units in each box. 📦
• Iterate through the sorted array elements and check the remaining `truckSize`.
• If not enough size for all boxes take as many boxes as you can and calculate the total units
• Else take all the boxes and calculate the total units.
• Return the total units

Code 🧑‍💻

``````var maximumUnits = function (boxTypes, truckSize) {
boxTypes.sort((a, b) => b - a);

var maxTotal = 0;
var i = 0;

while (truckSize > 0 && i < boxTypes.length) {
const numOfBoxes = boxTypes[i];
const numOfUnits = boxTypes[i];

if (truckSize <= numOfBoxes) {
maxTotal += truckSize * numOfUnits;
truckSize = 0;
} else {
maxTotal += numOfBoxes * numOfUnits;
truckSize -= numOfBoxes;
}

i++;
}
return maxTotal;
};``````

Time Complexity : O(nlogn)+O(n) = O(nlogn)

Space Complexity: O(1)

### Similar Questions for practice

Now it is time to try more similar questions