-
Notifications
You must be signed in to change notification settings - Fork 3
/
2462.cpp
41 lines (35 loc) · 1.04 KB
/
2462.cpp
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
31
32
33
34
35
36
37
38
39
40
41
typedef pair<int, int> P;
class Solution {
public:
long long totalCost(vector<int>& costs, int k, int candidates) {
int n = costs.size();
long long res = 0;
priority_queue<P, vector<P>, greater<P>> pq;
int left = candidates - 1;
int right = n - candidates;
for (int i = 0; i <= min(left, n - 1); ++i) {
pq.push({costs[i], i});
}
for (int i = max(left + 1, right); i < n; ++i) {
pq.push({costs[i], i});
}
left++;
right--;
while (k--) {
res += pq.top().first;
int index = pq.top().second;
pq.pop();
if (left <= right) {
if (index <= left) {
pq.push({costs[left], left});
left++;
}
else {
pq.push({costs[right], right});
right--;
}
}
}
return res;
}
};