Untitled
unknown
java
2 years ago
1.6 kB
17
Indexable
class Result {
/*
* Complete the 'getMaxUnits' function below.
*
* The function is expected to return a LONG_INTEGER.
* The function accepts following parameters:
* 1. LONG_INTEGER_ARRAY boxes
* 2. LONG_INTEGER_ARRAY unitsPerBox
* 3. LONG_INTEGER truckSize
*/
public static long getMaxUnits(List<Long> boxes, List<Long> unitsPerBox, long truckSize) {
// Create a list of box-unit pairs
List<BoxUnitPair> pairs = new ArrayList<>();
for (int i = 0; i < boxes.size(); i++) {
pairs.add(new BoxUnitPair(boxes.get(i), unitsPerBox.get(i)));
}
// Sort the pairs based on units in each box in descending order
pairs.sort((p1, p2) -> Long.compare(p2.units, p1.units));
long totalUnits = 0;
for (BoxUnitPair pair : pairs) {
// If we can fit all boxes of this product, add all the units to the total
if (truckSize >= pair.boxes) {
totalUnits += pair.boxes * pair.units;
truckSize -= pair.boxes;
} else {
// If we can only fit a portion of the boxes, fill the remaining space
totalUnits += truckSize * pair.units;
break;
}
// If the truck is full, we break out of the loop
if (truckSize == 0) break;
}
return totalUnits;
}
static class BoxUnitPair {
long boxes;
long units;
BoxUnitPair(long boxes, long units) {
this.boxes = boxes;
this.units = units;
}
}
}Editor is loading...
Leave a Comment