From ab78965115e7cdb7679f949cfeedc770e073ee19 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Fri, 29 Dec 2023 13:40:49 +0100 Subject: [PATCH] =?UTF-8?q?java:=20add=20=E2=80=9C2706.=20Buy=20Two=20Choc?= =?UTF-8?q?olates=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- java/buy-two-chocolates.java | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 java/buy-two-chocolates.java diff --git a/java/buy-two-chocolates.java b/java/buy-two-chocolates.java new file mode 100644 index 0000000..65962be --- /dev/null +++ b/java/buy-two-chocolates.java @@ -0,0 +1,21 @@ +class Solution { + public int buyChoco(int[] prices, int money) { + int[] mins = new int[2]; + mins[0] = mins[1] = Integer.MAX_VALUE; + + for (int p : prices) { + if (p < mins[0]) { + mins[1] = mins[0]; + mins[0] = p; + } else if (p < mins[1]) { + mins[1] = p; + } + } + + int leftover = money - mins[0] - mins[1]; + if (leftover < 0) { + return money; + } + return leftover; + } +}