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

Beautiful Towers II - Monotonic Increasing Stack [JS]

Check if There is a Valid Partition For The Array - Two Approaches - DP & Recursion w/ Memoization [JS]

Minimum Number of Operations to Sort a Binary Tree by Level - BFS & Cycle Counting Explained [JS]

Count Elements With Maximum Frequency - Hashmap [JS]

Mice and Cheese - Greedy w/ Sorting [JS]