From 43d48f5fcc21290a993185e8b7967d9a9f88aa21 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Mon, 2 Sep 2024 22:22:20 +0200 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB1894.=20Find=20the=20Studen?= =?UTF-8?q?t=20that=20Will=20Replace=20the=20Chalk=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- ...e-student-that-will-replace-the-chalk.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 java/find-the-student-that-will-replace-the-chalk.java diff --git a/java/find-the-student-that-will-replace-the-chalk.java b/java/find-the-student-that-will-replace-the-chalk.java new file mode 100644 index 0000000..16bdaa0 --- /dev/null +++ b/java/find-the-student-that-will-replace-the-chalk.java @@ -0,0 +1,31 @@ +class Solution { + private long getSum(int[] chalk, int k) { + long sum = 0; + + for (int uses : chalk) { + sum += uses; + if (sum > k) { + break; + } + } + + return sum; + } + + public int chalkReplacer(int[] chalk, int k) { + var partialSum = getSum(chalk, k); + + // Remove whole iterations over the students + k %= partialSum; + + for (int i = 0; i < chalk.length; ++i) { + if (k < chalk[i]) { + return i; + } + + k -= chalk[i]; + } + + return 0; + } +}