From 5c968ef14904afda02439a11bec63a0153372cf6 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 6 Jun 2024 11:38:33 +0200 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB846.=20Hand=20of=20Straight?= =?UTF-8?q?s=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- java/hand-of-straights.java | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 java/hand-of-straights.java diff --git a/java/hand-of-straights.java b/java/hand-of-straights.java new file mode 100644 index 0000000..e21f0ac --- /dev/null +++ b/java/hand-of-straights.java @@ -0,0 +1,34 @@ +import java.util.TreeMap; + +class Solution { + public boolean isNStraightHand(int[] hand, int groupSize) { + if (hand.length % groupSize != 0) { + return false; + } + + TreeMap cards = new TreeMap<>(); + for (int card : hand) { + cards.compute(card, (c, present) -> 1 + ((present == null) ? 0 : present)); + } + + while (!cards.isEmpty()) { + int card = cards.entrySet().iterator().next().getKey(); + + for (int i = 0; i < groupSize; ++i) { + // card doesn't exist + if (!cards.containsKey(card + i)) { + return false; + } + + cards.put(card + i, cards.get(card + i) - 1); + + // remove entry of used cards + if (cards.get(card + i) == 0) { + cards.remove(card + i); + } + } + } + + return true; + } +}