Sponsored
Sponsored
This method uses a line sweep technique, where we process the critical points along the time axis. We treat each event start time as a +1 (which indicates a new event starts), and each end time as a -1 (indicating an event ends).
By maintaining a running sum, we can identify the maximum overlap of events, which gives us the maximum k-booking at any point.
Time Complexity: O(N log N) due to sorting.
Space Complexity: O(N) for storing the timeline of events, where N is the number of events booked.
1class MyCalendarThree:
2 def __init__(self):
3 self.timeline = []
4
5 def book(self, start: int, end: int) -> int:
6 self.timeline.append((start, 1))
7 self.timeline.append((end, -1))
8
9 self.timeline.sort()
10
11 max_k, current_k = 0, 0
12 for time, value in self.timeline:
13 current_k += value
14 max_k = max(max_k, current_k)
15
16 return max_kIn this Python implementation, we maintain a list of tuples representing time points and their effects (+1 or -1). We sort these time points and iterate over them to calculate the maximum overlapping intervals, thus obtaining the maximum k-booking.
A more advanced approach involves using a balanced tree map (or balanced tree data structure) to manage events and efficiently find the maximum overlap.
The map holds start and end times as keys and their occurrences as values. By efficiently summing these up, we can determine the maximum k-booking.
Time Complexity: O(N log N) for the operations on a balanced tree.
Space Complexity: O(N) traversing the sorted keys when booking new events.
1using System;
2using System.Collections.Generic;
3
4public class MyCalendarThree {
5 private SortedDictionary<int, int> timeline;
public MyCalendarThree() {
timeline = new SortedDictionary<int, int>();
}
public int Book(int start, int end) {
if (!timeline.ContainsKey(start)) timeline[start] = 0;
if (!timeline.ContainsKey(end)) timeline[end] = 0;
timeline[start]++;
timeline[end]--;
int active = 0, maxK = 0;
foreach (var entry in timeline) {
active += entry.Value;
maxK = Math.Max(maxK, active);
}
return maxK;
}
}This C# solution uses a SortedDictionary to act like a balanced binary search tree. We increment the value for a start time and decrement for an end time. The running sum of values reflects the number of active events at any time.