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

题目描述:

2462. 雇佣 K 位工人的总代价_第1张图片

主要思路:

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

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;
    }
};

你可能感兴趣的:(Leetcode,java,算法,数据结构)