Minimum Cost to Hire K Workers

Sort by ratio, then maintain a max-heap of qualities — pay the minimum possible at each ratio threshold.

Hard
Time O(n log n) Space O(n)
LeetCode
6 min read
top-k heaps sorting

Problem#

Each worker has quality[i] and minimum wage[i]. Hire exactly k. Every hired worker is paid in proportion to quality, all relative to one ratio. Each must earn ≥ their wage. Minimize total payment.

Examples#

  • quality = [10,20,5], wage = [70,50,30], k = 2105.0

Constraints#

  • 1 <= k <= n <= 10^4.

Hints#

Hint 1
Per worker, the minimum ratio they accept is wage[i] / quality[i]. The hiring ratio is max over hired workers’ minima.

Approach#

Sort by wage / quality ratio ascending. Iterate; maintain a max-heap of qualities (kept in the team). After adding each worker as the new “max-ratio” worker, the team is the k workers with smallest quality sum, paid at the current ratio. Track the minimum cost.

Solution#

Min Cost to Hire K Workers
class Solution {
public:
double mincostToHireWorkers(vector<int>& quality, vector<int>& wage, int k) {
int n = quality.size();
vector<pair<double,int>> w(n);
for (int i = 0; i < n; ++i) w[i] = {(double)wage[i] / quality[i], quality[i]};
sort(w.begin(), w.end());
priority_queue<int> pq;
int sumQ = 0;
double best = 1e18;
for (auto& [r, q] : w) {
sumQ += q;
pq.push(q);
if ((int)pq.size() > k) { sumQ -= pq.top(); pq.pop(); }
if ((int)pq.size() == k) best = min(best, sumQ * r);
}
return best;
}
};

Editorial#

The minimum ratio that satisfies all hired workers is the maximum of their individual wage/quality ratios. Iterating in ratio order means the current worker’s ratio is exactly that team max. To minimize cost at that ratio, minimize the sum of qualities in the team — that’s a max-heap of size k holding the smallest qualities seen so far.

Complexity#

  • Time: O(n log n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.