43 lines
1 KiB
Java
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;
|
|
}
|
|
}
|