Skip to content

Commit d12afc9

Browse files
solves maximum units on a truck
1 parent ecfdcae commit d12afc9

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -420,7 +420,7 @@
420420
| 1700 | [Number of Students Unable to Eat Lunch](https://leetcode.com/problems/number-of-students-unable-to-eat-lunch) | [![Java](assets/java.png)](src/NumberOfStudentsUnableToEatLunch.java) | |
421421
| 1704 | [Determine if String Halves Are Alike](https://leetcode.com/problems/determine-if-string-halves-are-alike) | [![Java](assets/java.png)](src/DetermineIfStringHalvesAreAlike.java) | |
422422
| 1708 | 🔒 [Largest Subarray Length K](https://leetcode.com/problems/largest-subarray-length-k/) | | |
423-
| 1710 | [Maximum Units on a Truck](https://leetcode.com/problems/maximum-units-on-a-truck/) | | |
423+
| 1710 | [Maximum Units on a Truck](https://leetcode.com/problems/maximum-units-on-a-truck/) | [![Java](assets/java.png)](src/MaximumUnitsOnATruck.java) | |
424424
| 1716 | [Calculate Money in Leetcode Bank](https://leetcode.com/problems/calculate-money-in-leetcode-bank) | | |
425425
| 1720 | [Decode XORed Array](https://leetcode.com/problems/decode-xored-array) | | |
426426
| 1725 | [Number Of Rectangles That Can Form The Largest Square](https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square) | | |

Diff for: src/MaximumUnitsOnATruck.java

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

0 commit comments

Comments
 (0)