Skip to content

3439. Reschedule Meetings for Maximum Free Time I 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
 public:
  int maxFreeTime(int eventTime, int k, vector<int>& startTime,
                  vector<int>& endTime) {
    const vector<int> gaps = getGaps(eventTime, startTime, endTime);
    int windowSum = accumulate(gaps.begin(), gaps.begin() + k + 1, 0);
    int ans = windowSum;

    for (int i = k + 1; i < gaps.size(); ++i) {
      windowSum += gaps[i] - gaps[i - k - 1];
      ans = max(ans, windowSum);
    }

    return ans;
  }

 private:
  vector<int> getGaps(int eventTime, const vector<int>& startTime,
                      const vector<int>& endTime) {
    vector<int> gaps{startTime[0]};
    for (int i = 1; i < startTime.size(); ++i)
      gaps.push_back(startTime[i] - endTime[i - 1]);
    gaps.push_back(eventTime - endTime.back());
    return gaps;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public int maxFreeTime(int eventTime, int k, int[] startTime, int[] endTime) {
    int[] gaps = getGaps(eventTime, startTime, endTime);
    int windowSum = Arrays.stream(gaps, 0, k + 1).sum();
    int ans = windowSum;

    for (int i = k + 1; i < gaps.length; i++) {
      windowSum += gaps[i] - gaps[i - k - 1];
      ans = Math.max(ans, windowSum);
    }

    return ans;
  }

  private int[] getGaps(int eventTime, int[] startTime, int[] endTime) {
    int[] gaps = new int[startTime.length + 1];
    gaps[0] = startTime[0];
    for (int i = 1; i < startTime.length; ++i)
      gaps[i] = startTime[i] - endTime[i - 1];
    gaps[startTime.length] = eventTime - endTime[endTime.length - 1];
    return gaps;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def maxFreeTime(
      self,
      eventTime: int,
      k: int,
      startTime: list[int],
      endTime: list[int]
  ) -> int:
    gaps = ([startTime[0]] +
            [startTime[i] - endTime[i - 1] for i in range(1, len(startTime))] +
            [eventTime - endTime[-1]])
    windowSum = sum(gaps[:k + 1])
    ans = windowSum

    for i in range(k + 1, len(gaps)):
      windowSum += gaps[i] - gaps[i - k - 1]
      ans = max(ans, windowSum)

    return ans