09. Minimum Cost to Hire K Workers
There are n workers given by quality and wage arrays. You want to hire exactly k workers such that every worker is paid at least their minimum wage and worker pay is proportional to their quality. Return the minimum cost to form a valid team.
How It Works & Algorithmic Design
Solves using Ratio Sorting + Max-Heap Quality Tracking:
- Ratio Computation: For each worker, compute
wage / qualityratio. Sort workers by this unit ratio in ascending order. - Max-Heap: Track top $k$ smallest qualities seen so far using Max-Heap
maxHeapand running sumtotalQuality. - Greedy Traversal: For each worker ratio $R$:
- Add
qualitytomaxHeapandtotalQuality += quality. - If
maxHeap.size > k, pop largest qualitytopand subtracttotalQuality -= top. - If
maxHeap.size === k: calculate candidate costtotalQuality * Rand updateminCost.
- Add
Why This Approach Works Best
Sorting ratios ensures wage minimums are respected while Max-Heap prunes high quality workers to optimize total cost in $O(n \log n)$ time.
Example Walkthrough
quality = [10,20,5], wage = [70,50,30], k = 2
Workers data.
Hire worker 1 (ratio 2.5) and worker 2 (ratio 6.0) -> cost 105.0.
Minimal wage cost.
105.00000
Minimum total cost.
Answer: Minimum Cost to Hire K Workers implementation
function mincostToHireWorkers(quality, wage, k) {
const workers = quality.map((q, i) => ({ q, r: wage[i] / q }));
workers.sort((a, b) => a.r - b.r);
const heap = []; // Simulated Max-Heap
let totalQuality = 0;
let minCost = Infinity;
for (const w of workers) {
heap.push(w.q);
heap.sort((a, b) => b - a);
totalQuality += w.q;
if (heap.length > k) {
totalQuality -= heap.shift();
}
if (heap.length === k) {
minCost = Math.min(minCost, totalQuality * w.r);
}
}
return minCost;
}Sort workers by wage-to-quality ratio and use max-heap to keep quality sum minimal.
Team cost is determined by max worker ratio $\times$ total team quality.
Max-heap evicts highest quality worker to keep total team quality minimal.
Sorting ratios guarantees worker wage constraints are met.