-
Notifications
You must be signed in to change notification settings - Fork 16
/
MaximumUnitsOnATruck.java
43 lines (38 loc) · 1.21 KB
/
MaximumUnitsOnATruck.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.util.ArrayList;
import java.util.List;
public class MaximumUnitsOnATruck {
public int maximumUnits(int[][] boxTypes, int truckSize) {
final List<BoxType> boxes = getBoxTypesFrom(boxTypes);
boxes.sort(BoxType::compareTo);
int units = 0;
for (BoxType box : boxes) {
if (box.number <= truckSize) {
units += box.units * box.number;
truckSize -= box.number;
} else {
units += box.units * truckSize;
break;
}
}
return units;
}
private List<BoxType> getBoxTypesFrom(int[][] boxes) {
final List<BoxType> boxTypes = new ArrayList<>();
for (int[] box : boxes) {
boxTypes.add(new BoxType(box[0], box[1]));
}
return boxTypes;
}
private static final class BoxType implements Comparable<BoxType> {
private final int number;
private final int units;
private BoxType(int number, int units) {
this.number = number;
this.units = units;
}
@Override
public int compareTo(BoxType o) {
return Integer.compare(o.units, this.units);
}
}
}