java: add «2462. Total Cost to Hire K Workers»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
4b297be824
commit
4fc9cb0a11
1 changed files with 43 additions and 0 deletions
43
java/total-cost-to-hire-k-workers.java
Normal file
43
java/total-cost-to-hire-k-workers.java
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue