From a1dc25b5e50e16cb021a4f3a9455c5cb43987d05 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 8 Dec 2024 22:39:25 +0100 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB2054.=20Two=20Best=20Non-Ov?= =?UTF-8?q?erlapping=20Events=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/two-best-non-overlapping-events/ Signed-off-by: Matej Focko --- java/two-best-non-overlapping-events.java | 29 +++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 java/two-best-non-overlapping-events.java diff --git a/java/two-best-non-overlapping-events.java b/java/two-best-non-overlapping-events.java new file mode 100644 index 0000000..6a9dcf1 --- /dev/null +++ b/java/two-best-non-overlapping-events.java @@ -0,0 +1,29 @@ +class Solution { + private static final int END = 0; + private static final int START = 1; + + private record Event(int time, int type, int payoff) {} + + public int maxTwoEvents(int[][] events) { + var times = new ArrayList(); + for (var event : events) { + times.add(new Event(event[0], START, event[2])); + times.add(new Event(event[1] + 1, END, event[2])); + } + times.sort(Comparator.comparing(Event::time).thenComparing(Event::type)); + + int answer = 0, maxPayoff = 0; + for (var time : times) { + switch (time.type) { + case START: + answer = Math.max(answer, time.payoff + maxPayoff); + break; + case END: + maxPayoff = Math.max(maxPayoff, time.payoff); + break; + } + } + + return answer; + } +}