#3440
Reschedule Meetings for Maximum Free Time II
MediumArrayGreedyEnumerationGreedySortingEnumeration
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution sorts the meetings and then calculates the maximum free time by considering the gaps between meetings. It efficiently checks if moving one meeting can create a larger gap, maximizing free time.
⚙️
Algorithm
4 steps- 1Step 1: Create a list of meetings as pairs of (startTime[i], endTime[i]).
- 2Step 2: Sort the meetings based on their end times.
- 3Step 3: Calculate the free time between consecutive meetings and find the maximum free time.
- 4Step 4: For each meeting, check if moving it to the previous or next free gap can increase the maximum free time.
solution.py30 lines
1# Full working Python code
2
3def maxFreeTime(eventTime, startTime, endTime):
4 meetings = sorted(zip(startTime, endTime))
5 max_free_time = 0
6 prev_end = 0
7 gaps = []
8
9 for start, end in meetings:
10 max_free_time = max(max_free_time, start - prev_end)
11 gaps.append((prev_end, start))
12 prev_end = end
13
14 # Check moving each meeting
15 for i in range(len(meetings)):
16 start, end = meetings[i]
17 duration = end - start
18 # Check moving earlier
19 if i > 0:
20 new_start = meetings[i - 1][1]
21 if new_start + duration <= eventTime:
22 max_free_time = max(max_free_time, new_start - gaps[i - 1][0])
23 # Check moving later
24 if i < len(meetings) - 1:
25 new_end = meetings[i + 1][0]
26 if new_end - duration >= 0:
27 max_free_time = max(max_free_time, gaps[i][1] - new_end)
28
29 return max_free_time
30ℹ
Complexity note: The sorting step takes O(n log n) time, and we use O(n) space to store the meetings and gaps.
- 1Gaps between meetings can be maximized by considering moving one meeting.
- 2Sorting meetings helps in efficiently calculating free time.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.