2462. 雇佣 K 位工人的总代价

雇佣 K 位工人的总代价

解法一: 优先级队列

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public long totalCost(int[] costs, int k, int candidates) {
PriorityQueue<Integer> leftQueue = new PriorityQueue<>((num1, num2) -> num1 - num2);
PriorityQueue<Integer> rightQueue = new PriorityQueue<>((num1, num2) -> num1 - num2);
int n = costs.length;
int left = 0;
int right = n - 1;
for (int i = 0; i < candidates && left <= right; i++) {
leftQueue.offer(costs[left++]);
if (left <= right) {
rightQueue.offer(costs[right--]);
}
}
long ans = 0L;
while (k-- > 0) {
if (leftQueue.isEmpty() || !rightQueue.isEmpty() && leftQueue.peek() > rightQueue.peek()) {
ans += rightQueue.poll();
while (left <= right && rightQueue.size() < candidates) {
rightQueue.offer(costs[right--]);
}
} else {
ans += leftQueue.poll();
while (left <= right && leftQueue.size() < candidates) {
leftQueue.offer(costs[left++]);
}
}
}
return ans;
}
}
作者

wuhunyu

发布于

2024-05-01

更新于

2024-05-01

许可协议