Maximum Building Height LeetCode solution in JavaScript

1
/**
2
* @param {number} n
3
* @param {number[][]} restrictions
4
* @return {number}
5
*/
6
var maxBuilding = function (n, restrictions) {
7
let maxHeight = 0;
8
restrictions.push([1, 0]); //Push extra restriction as 0 for 1
9
restrictions.push([n, n - 1]); //Push extra restrition as n-1 for n
10
restrictions.sort(function (a, b) {
11
return a[0] - b[0];
12
});
13
//Propogate from left to right to tighten the restriction: Check building restriction can be furhter tightened due to the left side building restriction.
14
for (let i = 1; i < restrictions.length; i++) {
15
restrictions[i][1] = Math.min(
16
restrictions[i][1],
17
restrictions[i][0] - restrictions[i - 1][0] + restrictions[i - 1][1]
18
);
19
}
20
//Propogate from right to left to tighten the restriction: Check building restriction can be furhter tightened due to the right side building restriction.
21
for (let i = restrictions.length - 2; i >= 0; i--) {
22
restrictions[i][1] = Math.min(
23
restrictions[i][1],
24
restrictions[i + 1][0] - restrictions[i][0] + restrictions[i + 1][1]
25
);
26
}
27
let max = 0;
28
for (let i = 0; i < restrictions.length - 1; i++) {
29
let leftHeight = restrictions[i][1];
30
let rightHeight = restrictions[i + 1][1];
31
let distance = restrictions[i + 1][0] - restrictions[i][0] - 1; //Number of cities between ith and i+1th city, excluding these cities
32
let hightDiff = Math.abs(restrictions[i + 1][1] - restrictions[i][1]);
33
let middleHeight =
34
Math.max(leftHeight, rightHeight) + Math.ceil((distance - hightDiff) / 2);
35
max = Math.max(max, middleHeight);
36
}
37
return max;
38
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0