[LeetCode] Minimum Cost to Hire K Workers

857. Minimum Cost to Hire K Workers

There are n workers. You are given two integer arrays quality and wage where quality[i] is the quality of the ith worker and wage[i] is the minimum wage expectation for the ith worker.

We want to hire exactly k workers to form a paid group. To hire a group of k workers, we must pay them according to the following rules:

  1. Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
  2. Every worker in the paid group must be paid at least their minimum wage expectation.

Given the integer k, return the least amount of money needed to form a paid group satisfying the above conditions. Answers within 10-5 of the actual answer will be accepted.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
double mincostToHireWorkers(vector<int>& q, vector<int>& w, int k) {
double res = DBL_MAX;
vector<pair<double, int>> vec;
for(int i = 0; i < q.size(); i++) {
vec.push_back({1.0 * w[i] / q[i], q[i]});
}

sort(vec.begin(), vec.end());
priority_queue<int> pq;
int tot = 0;
for(auto& [ratio, qua] : vec) {
tot += qua;
pq.push(qua);
if(pq.size() > k) {tot -= pq.top(); pq.pop();}
if(pq.size() == k) res = min(res, tot * ratio);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/04/PS/LeetCode/minimum-cost-to-hire-k-workers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.