Maximum Building Height LeetCode solution in Java

1
class Solution {
2
public int maxBuilding(int n, int[][] restrictions) {
3
List<int[]> list = new ArrayList<>();
4
list.add(new int[] {1, 0});
5
for (int[] restriction : restrictions) {
6
list.add(restriction);
7
}
8
Collections.sort(list, new IDSorter());
9

10
if (list.get(list.size() - 1)[0] != n) {
11
list.add(new int[] {n, n - 1});
12
}
13

14
for (int i = 1; i < list.size(); i++) {
15
list.get(i)[1] =
16
Math.min(list.get(i)[1], list.get(i - 1)[1] + list.get(i)[0] - list.get(i - 1)[0]);
17
}
18

19
for (int i = list.size() - 2; i >= 0; i--) {
20
list.get(i)[1] =
21
Math.min(list.get(i)[1], list.get(i + 1)[1] + list.get(i + 1)[0] - list.get(i)[0]);
22
}
23

24
int result = 0;
25
for (int i = 1; i < list.size(); i++) {
26
int h1 = list.get(i - 1)[1]; // heigth of previous restriction
27
int h2 = list.get(i)[1]; // height of current restriction
28
int x = list.get(i - 1)[0]; // id of previous restriction
29
int y = list.get(i)[0]; // id of current restriction
30

31
result = Math.max(result, Math.max(h1, h2) + (y - x - Math.abs(h1 - h2)) / 2);
32
}
33
return result;
34
}
35

36
public class IDSorter implements Comparator<int[]> {
37
@Override
38
public int compare(int[] myself, int[] other) {
39
return myself[0] - other[0];
40
}
41
}
42
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0