Fill The Truck - Company-specific OAs / Amazon OA

https://algo.monster/problems/fill_the_truck

javascript:

function maximumUnits(boxTypes, truckSize) {
// sorted desc
boxTypes.sort((a,b) => b[1] - a[1])
let maxUnits = 0

for (let i = 0; i < boxTypes.length; i++) {
const [totalBox, totalUnits] = boxTypes[i]

if (truckSize > 0) {
let unitTaken = Math.min(totalBox, truckSize)
truckSize -= unitTaken
maxUnits += totalBox * unitTaken
} else {
return totalUnit
}
}
return totalUnits
}

public int maximumUnits(int[][] boxTypes, int truckSize) {
TreeMap<Integer, Integer> tm = new TreeMap<>(Comparator.reverseOrder());
int boxesLeft = truckSize;
int answer = 0;

    for (int i = 0; i < boxTypes.length; i++) {
        int value = boxTypes[i][0];
        if (tm.containsKey(boxTypes[i][1])) {
            value += tm.get(boxTypes[i][1]);
        }
        tm.put(boxTypes[i][1], value);
    }
    
    for (Map.Entry<Integer, Integer> e : tm.entrySet()) {
        int units = e.getKey();
        int boxes = Math.min(boxesLeft, e.getValue());
        
        answer += boxes * units;
        boxesLeft -= boxes;
        
        if (boxesLeft == 0)
            break;
    }
    
    return answer;
}