力扣2462.雇佣K位工人的总代价
- 当2*can + k > n时
- 最终结果一定为cost中前k个最小数
- 且当2*can + k <= n时
- 两小根堆一定不会有交集
-
class Solution { public: long long totalCost(vector<int>& costs, int k, int candidates) { int n = costs.size(); if(candidates * 2 + k > n) { ranges::sort(costs); return accumulate(costs.begin(),cost.begin() + k , 0LL); } priority_queue<int,vector<int>,greater<int>> pre,suf; for(int i=0;i<candidates;i++) { pre.push(cost[i]); suf.push(cost[n-1-i]); } long long res=0; int i = candidates,j = n - 1 - candidates; while(k --) { if(pre.top() <= suf.top()) { res += pre.top(); pre.pop(); pre.push(costs[i++]); } else { res += suf.top(); suf.pop(); suf.push(cost[j--]); } } return res; } };