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

题目描述:

在这里插入图片描述

主要思路:

分别维护两个堆,取左右两边最小的那个。

class Solution {
    
    
public:
    long long totalCost(vector<int>& costs, int k, int candidates) {
    
    
        priority_queue<int,vector<int>,greater<int>> ql,qr;
        int l=0,r=costs.size()-1;
        long long ans=0;
        while(k--)
        {
    
    
            while(ql.size()<candidates&&l<=r)
                ql.push(costs[l++]);
            while(qr.size()<candidates&&r>=l)
                qr.push(costs[r--]);
            int a=ql.size()?ql.top():INT_MAX,b=qr.size()?qr.top():INT_MAX;
            if(a<=b)
            {
    
    
                ans+=a;
                ql.pop();
            }
            else
            {
    
    
                ans+=b;
                qr.pop();
            }
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_54385104/article/details/132185457