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.
1#include <map>
2using namespace std;
3
4class MyCalendarThree {
5 map<int, int> timeline;
public:
MyCalendarThree() {}
int book(int start, int end) {
timeline[start]++;
timeline[end]--;
int maxK = 0, active = 0;
for (auto& [time, count] : timeline) {
active += count;
maxK = max(maxK, active);
}
return maxK;
}
};This C++ implementation employs std::map as a balanced tree to store the impact (+1, -1) at each start and end time. It iterates over the sorted keys to measure the overlapping events count.