From 4fc9cb0a11457d5f6b0684eaf374b3cbe190d268 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Mon, 12 Aug 2024 17:10:26 +0200 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB2462.=20Total=20Cost=20to?= =?UTF-8?q?=20Hire=20K=20Workers=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- java/total-cost-to-hire-k-workers.java | 43 ++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 java/total-cost-to-hire-k-workers.java diff --git a/java/total-cost-to-hire-k-workers.java b/java/total-cost-to-hire-k-workers.java new file mode 100644 index 0000000..4a10d08 --- /dev/null +++ b/java/total-cost-to-hire-k-workers.java @@ -0,0 +1,43 @@ +import java.util.Comparator; +import java.util.PriorityQueue; + +class Solution { + private record Worker(int cost, int queue) {} + + private static final Comparator WORKER_CMP = + Comparator.comparing(Worker::cost).thenComparing(Worker::queue); + + public long totalCost(int[] costs, int k, int candidates) { + var q = new PriorityQueue(WORKER_CMP); + + // Add left side + for (int i = 0; i < candidates; ++i) { + q.offer(new Worker(costs[i], 0)); + } + + // Add right side + for (int i = Math.max(candidates, costs.length - candidates); i < costs.length; ++i) { + q.offer(new Worker(costs[i], 1)); + } + + long cost = 0; + + int l = candidates, r = costs.length - 1 - candidates; + for (int i = 0; i < k; ++i) { + var worker = q.poll(); + cost += worker.cost(); + + if (l <= r) { + if (worker.queue() == 0) { + q.offer(new Worker(costs[l], 0)); + ++l; + } else { + q.offer(new Worker(costs[r], 1)); + --r; + } + } + } + + return cost; + } +}