1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-16 16:36:56 +02:00
LeetCode/java/total-cost-to-hire-k-workers.java
Matej Focko 4fc9cb0a11
java: add «2462. Total Cost to Hire K Workers»
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-08-12 17:10:26 +02:00

43 lines
1 KiB
Java

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;
}
}