LeetCode/cs/my-calendar-ii.cs
Matej Focko fd54db95cd
cs: add «731. My Calendar II»
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-09-27 21:51:21 +02:00

31 lines
818 B
C#

public class MyCalendarTwo {
private SortedDictionary<int, int> counters = [];
private int maxOverlaps = 2;
public MyCalendarTwo() { }
public bool Book(int start, int end) {
counters[start] = counters.GetValueOrDefault(start, 0) + 1;
counters[end] = counters.GetValueOrDefault(end, 0) - 1;
var overlaps = 0;
foreach (var pair in counters) {
var (_, count) = (pair.Key, pair.Value);
overlaps += count;
if (overlaps > maxOverlaps) {
counters[start] = counters[start] - 1;
counters[end] = counters[end] + 1;
if (counters[start] == 0) {
counters.Remove(start);
}
return false;
}
}
return true;
}
}