Maximum Units on a Truck

easy greedy sorting

Problem

Given boxTypes[i] = [numBoxes, unitsPerBox] and truckSize, return the maximum total units that fit.

InputboxTypes = [[1,3],[2,2],[3,1]], truckSize = 4
Output8
Take 1×3 + 2×2 + 1×1 = 8 units.

def maximum_units(boxTypes, truckSize):
    boxTypes.sort(key=lambda b: -b[1])
    ans = 0
    for cnt, u in boxTypes:
        take = min(cnt, truckSize)
        ans += take * u
        truckSize -= take
        if truckSize == 0: break
    return ans
function maximumUnits(boxTypes, truckSize) {
  boxTypes.sort((a, b) => b[1] - a[1]);
  let ans = 0;
  for (const [cnt, u] of boxTypes) {
    const take = Math.min(cnt, truckSize);
    ans += take * u; truckSize -= take;
    if (truckSize === 0) break;
  }
  return ans;
}
class Solution {
    public int maximumUnits(int[][] boxTypes, int truckSize) {
        Arrays.sort(boxTypes, (a, b) -> b[1] - a[1]);
        int ans = 0;
        for (int[] b : boxTypes) {
            int take = Math.min(b[0], truckSize);
            ans += take * b[1];
            truckSize -= take;
            if (truckSize == 0) break;
        }
        return ans;
    }
}
int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {
    sort(boxTypes.begin(), boxTypes.end(), [](auto& a, auto& b){ return a[1] > b[1]; });
    int ans = 0;
    for (auto& b : boxTypes) {
        int take = min(b[0], truckSize);
        ans += take * b[1]; truckSize -= take;
        if (truckSize == 0) break;
    }
    return ans;
}
Time: O(n log n) Space: O(1)