Skip to content

1710. Maximum Units on a Truck 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {
    int ans = 0;

    ranges::sort(boxTypes, ranges::greater{},
                 [](const vector<int>& boxType) { return boxType[1]; });

    for (const vector<int>& boxType : boxTypes) {
      const int boxes = boxType[0];
      const int units = boxType[1];
      if (boxes >= truckSize)
        return ans + truckSize * units;
      ans += boxes * units;
      truckSize -= boxes;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int maximumUnits(int[][] boxTypes, int truckSize) {
    int ans = 0;

    Arrays.sort(boxTypes, (a, b) -> Integer.compare(b[1], a[1]));

    for (int[] boxType : boxTypes) {
      final int boxes = boxType[0];
      final int units = boxType[1];
      if (boxes >= truckSize)
        return ans + truckSize * units;
      ans += boxes * units;
      truckSize -= boxes;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def maximumUnits(self, boxTypes: list[list[int]], truckSize: int) -> int:
    ans = 0

    for boxes, units in sorted(boxTypes, key=lambda x: -x[1]):
      if boxes >= truckSize:
        return ans + truckSize * units
      ans += boxes * units
      truckSize -= boxes

    return ans