Skip to main content
Back to problems
#1710
Easy Algorithms

Maximum units on a truck

Array Greedy Sorting
74.7% acceptance
Feb 25, 2026
4021
239
You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]: numberOfBoxesi is the number of boxes of type i. numberOfUnitsPerBoxi is the number of units in each box of the 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

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn maximum_units(mut box_types: Vec<Vec<i32>>, truck_size: i32) -> i32 {
    box_types.sort_unstable_by(|a, b| b[1].cmp(&a[1]));
    let mut remaining = truck_size;
    let mut total = 0;
    for b in &box_types {
      if remaining <= 0 { break; }
      let take = remaining.min(b[0]);
      total += take * b[1];
      remaining -= take;
    }
    total
  }
}