1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-16 16:36:56 +02:00

java: add «2462. Total Cost to Hire K Workers»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-08-12 17:10:26 +02:00
parent 4b297be824
commit 4fc9cb0a11
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -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> WORKER_CMP =
Comparator.comparing(Worker::cost).thenComparing(Worker::queue);
public long totalCost(int[] costs, int k, int candidates) {
var q = new PriorityQueue<Worker>(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;
}
}