jayati

Total Cost to Hire K Workers

Jul 2nd, 2024
894
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     long long totalCost(vector<int>& costs, int k, int candidates) {
  4.         int n=costs.size();
  5.         priority_queue<int,vector<int>,greater<int>> pq1,pq2;
  6.  
  7.         long long ans=0;
  8.         int hired=0;
  9.         int i=0,j=n-1;
  10.         while(hired<k)
  11.         {
  12.             while(pq1.size()<candidates && i<=j)
  13.             {
  14.                 pq1.push(costs[i]);
  15.                 i++;
  16.             }
  17.             while(pq2.size()<candidates && j>=i)
  18.             {
  19.                 pq2.push(costs[j]);
  20.                 j--;
  21.             }
  22.             int min_pq1 = pq1.size()>0?pq1.top():INT_MAX;
  23.             int min_pq2 = pq2.size()>0?pq2.top():INT_MAX;
  24.             if(min_pq1<=min_pq2)
  25.             {
  26.                 ans+=min_pq1;
  27.                 pq1.pop();
  28.             }
  29.             else
  30.             {
  31.                 ans+=min_pq2;
  32.                 pq2.pop();
  33.             }
  34.             hired++;
  35.         }
  36.         return ans;
  37.     }
  38. };
Advertisement
Add Comment
Please, Sign In to add comment