Leet Code Daily 2024-05-11 - Minimum Cost to Hire K Workers
Solution
Let's say is the set of hired workers and is the cost of hired worker .
We know all hired workers must be paid equally.
And we also know the minimum wage .
The total cost would be:
Sort + Priority Queue
If we sort all workers by . Then, at any time, if worker is hired, all workers before can be hired with same . And we only need to maintain top-k workers with smallest before to find current minimum cost.
Time Complexity
Code
class Solution {
public:
double mincostToHireWorkers(vector<int>& quality, vector<int>& wage,
int k) {
vector<pair<int, int>> workers;
for (int i = 0; i < quality.size(); i++) {
workers.push_back(make_pair(quality[i], wage[i]));
}
sort(workers.begin(), workers.end(),
[](const pair<int, int>& x, const pair<int, int>& y) {
return x.second * y.first < y.second * x.first;
});
double ans = 1E9;
int total_quality = 0;
priority_queue<int> hired_workers;
for (const auto& w : workers) {
total_quality += w.first;
hired_workers.push(w.first);
while (hired_workers.size() > k) {
total_quality -= hired_workers.top();
hired_workers.pop();
}
if (hired_workers.size() == k) {
ans = min(ans, 1.0 * total_quality * w.second / w.first);
}
}
return ans;
}
};