Reschedule Meetings for Maximum Free Time I - Sliding Window - Constant Space [JS]

Description 

Solution: Sliding Window

Maintain a sliding window of size k + 2 and store the running sum of meetings within the window.
Within each window, move all meetings as left as possible or right as possible such that there is no space in between the meetings.
This maximizes the longest continuous gap.
This can be calculated by: last meeting start time - first meeting end time - sum of meeting durations in between first and last meetings.

Time Complexity: O(n)
Space Complexity: O(1)

JavaScript
function maxFreeTime(eventTime, k, startTime, endTime) {
  const n = startTime.length;
  let durationSum = 0, maxGap = 0;
  for (let i = 0; i < n; i++) {
    durationSum += endTime[i] - startTime[i];
    if (i >= k) {
      durationSum -= endTime[i - k] - startTime[i - k];
    }
    if (i >= k - 1) {
      const lastMeetingStart = i === n - 1 ? eventTime : startTime[i + 1];
      const firstMeetingEnd = i - k < 0 ? 0 : endTime[i - k];
      const gap = lastMeetingStart - firstMeetingEnd - durationSum;
      maxGap = Math.max(maxGap, gap);
    }
  }
  return maxGap;
};

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]