cs: add «731. My Calendar II»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-09-27 21:51:21 +02:00
parent 528d2350aa
commit fd54db95cd
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

31
cs/my-calendar-ii.cs Normal file
View file

@ -0,0 +1,31 @@
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;
}
}