From fd54db95cd7463b0ed48e47e4c72773a16f6e93d Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Fri, 27 Sep 2024 21:51:21 +0200 Subject: [PATCH] =?UTF-8?q?cs:=20add=20=C2=AB731.=20My=20Calendar=20II?= =?UTF-8?q?=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- cs/my-calendar-ii.cs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 cs/my-calendar-ii.cs diff --git a/cs/my-calendar-ii.cs b/cs/my-calendar-ii.cs new file mode 100644 index 0000000..91eee1d --- /dev/null +++ b/cs/my-calendar-ii.cs @@ -0,0 +1,31 @@ +public class MyCalendarTwo { + private SortedDictionary 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; + } +}