Maximum Consecutive Floors Without Special Floors - Sorting & Get Max Adjacent Difference [JS]
- Get link
- X
- Other Apps
By
Anna An
on
Solution: Sorting & Get Max Adjacent Difference
- Get all the special floors within the range of [bottom, ..., top].
Add the edge cases bottom - 1 and top + 1, these are the starting and ending floors within the range.
The reason for -1 and +1 is that when we compare adjacent floors, both floors are not part of the consecutive floors, but the starting and ending floor is. - Sort the floors.
- Get the max difference between two adjacent floors.
Time Complexity: O(n log(n))
366ms
Space Complexity: O(n)
60.3MB
var maxConsecutive = function(bottom, top, special) {
let floors = [bottom - 1, top + 1];
for (let floor of special) {
if (floor >= bottom && floor <= top) floors.push(floor);
}
floors.sort((a, b) => a - b);
let ans = 0;
for (let i = 1; i < floors.length; i++) {
ans = Math.max(ans, floors[i] - floors[i - 1] - 1);
}
return ans;
};
javascript
- Get link
- X
- Other Apps
Comments
Post a Comment