@@ -192,4 +192,85 @@ class Solution:
192192 best = len (heap)
193193 res = left
194194 return res
195+ ```
196+
197+ ### 2-2) My Calendar II
198+
199+ ``` java
200+ // java
201+ // LC 731 My Calendar II
202+ // V1-1
203+ // https://leetcode.com/problems/my-calendar-ii/editorial/
204+ // IDEA: Line Sweep (Scanning line)
205+ /**
206+ * IDEA:
207+ *
208+ *
209+ * 1) Class `MyCalendarTwo` will have two data members,
210+ * `maxOverlappedBooking` which is the maximum number of
211+ * concurrent bookings possible at a time,
212+ * and `bookingCount` which is a map from integer to integer
213+ * with the time point as the key and number of bookings as the value.
214+ *
215+ *
216+ * 2) Initialize `maxOverlappedBooking` as 2, as we need to check for triple booking.
217+ *
218+ * 3) Define the function book(start, end) as:
219+ *
220+ * - Increase the number of bookings for the time start and decrease
221+ * the number of bookings for end by 1 in the map bookingCount.
222+ *
223+ * - Iterate over each key-value pair in the map
224+ * in ascending order of keys to find the prefix sum.
225+ * Add the value in the map to the count overlappedBooking.
226+ *
227+ * - If overlappedBooking is more than two, it implies that this
228+ * is triple booking. Hence, we should return false.
229+ * Also, we need to revert the changes in the map as this booking shouldn't be added.
230+ *
231+ * - If we reach here, it implies no triple booking and hence returns true.
232+ *
233+ */
234+ class MyCalendarTwo_1_1 {
235+
236+
237+
238+ private TreeMap<Integer , Integer > bookingCount;
239+ private int maxOverlappedBooking;
240+
241+ public MyCalendarTwo_1_1 () {
242+ bookingCount = new TreeMap<> ();
243+ maxOverlappedBooking = 2 ;
244+ }
245+
246+ public boolean book (int start , int end ) {
247+ // Increase the booking count at 'start' and decrease at 'end'.
248+ bookingCount. put(start, bookingCount. getOrDefault(start, 0 ) + 1 );
249+ bookingCount. put(end, bookingCount. getOrDefault(end, 0 ) - 1 );
250+
251+ int overlappedBooking = 0 ;
252+
253+ // Calculate the prefix sum of bookings.
254+ for (Map . Entry<Integer , Integer > entry : bookingCount. entrySet()) {
255+ overlappedBooking += entry. getValue();
256+
257+ // If the number of overlaps exceeds the allowed limit, rollback and
258+ // return false.
259+ if (overlappedBooking > maxOverlappedBooking) {
260+ // Rollback changes.
261+ bookingCount. put(start, bookingCount. get(start) - 1 );
262+ bookingCount. put(end, bookingCount. get(end) + 1 );
263+
264+ // Clean up if the count becomes zero to maintain the map clean.
265+ if (bookingCount. get(start) == 0 ) {
266+ bookingCount. remove(start);
267+ }
268+
269+ return false ;
270+ }
271+ }
272+
273+ return true ;
274+ }
275+ }
195276```
0 commit comments