#732
Hard Algorithms My calendar iii
Binary Search Design Segment Tree Prefix Sum Ordered Set
71.5% acceptance
Feb 21, 2026
2081
275
A k-booking happens when k events have some non-empty intersection (i.e., there is some time that is common to all k events.)
You are given some events [startTime, endTime), after each given event, return an integer k representing the maximum k-booking between all the previous events.
Implement the MyCalendarThree class:
MyCalendarThree() Initializes the object.
int book(int startTime, int endTime) Returns an integer k representing the largest integer such that there exists a k-booking in the calendar.
Solution
Rust
Time O(n log n)
Space O(n)
/*
* A k-booking happens when k events have some non-empty intersection (i.e., there is some time that is common to all k events.)
* You are given some events [startTime, endTime), after each given event, return an integer k representing the maximum k-booking between all the previous events.
* Implement the MyCalendarThree class:
* MyCalendarThree() Initializes the object.
* int book(int startTime, int endTime) Returns an integer k representing the largest integer such that there exists a k-booking in the calendar.
* Example 1:
* Input
* ["MyCalendarThree", "book", "book", "book", "book", "book", "book"]
* [[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]
* Output
* [null, 1, 1, 2, 3, 3, 3]
* Explanation
* MyCalendarThree myCalendarThree = new MyCalendarThree();
* myCalendarThree.book(10, 20); // return 1
* myCalendarThree.book(50, 60); // return 1
* myCalendarThree.book(10, 40); // return 2
* myCalendarThree.book(5, 15); // return 3
* myCalendarThree.book(5, 10); // return 3
* myCalendarThree.book(25, 55); // return 3
* Constraints:
* 0 <= startTime < endTime <= 109
* At most 400 calls will be made to book.
* struct MyCalendarThree {
* }
* /**
* * `&self` means the method takes an immutable reference.
* * If you need a mutable reference, change it to `&mut self` instead.
* */
* impl MyCalendarThree {
* fn new() -> Self {
* }
* fn book(&self, start_time: i32, end_time: i32) -> i32 {
* }
* }
*/
use std::collections::BTreeMap;
struct MyCalendarThree {
delta: BTreeMap<i32, i32>,
}
impl MyCalendarThree {
fn new() -> Self {
MyCalendarThree { delta: BTreeMap::new() }
}
fn book(&mut self, start_time: i32, end_time: i32) -> i32 {
*self.delta.entry(start_time).or_insert(0) += 1;
*self.delta.entry(end_time).or_insert(0) -= 1;
let mut cur = 0;
let mut max = 0;
for &v in self.delta.values() {
cur += v;
if cur > max { max = cur; }
}
max
}
}