Maximum Consecutive Floors Without Special Floors - Sorting & Get Max Adjacent Difference [JS]

Description 

Solution: Sorting & Get Max Adjacent Difference

  1. 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.
  2. Sort the floors.
  3. 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

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]