09. Minimum Cost to Hire K Workers

Difficulty:HardPattern:Ratio Sorting + Max-HeapTime:O(n log n)Space:O(k)

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:

  1. Ratio Computation: For each worker, compute wage / quality ratio. Sort workers by this unit ratio in ascending order.
  2. Max-Heap: Track top $k$ smallest qualities seen so far using Max-Heap maxHeap and running sum totalQuality.
  3. Greedy Traversal: For each worker ratio $R$:
    • Add quality to maxHeap and totalQuality += quality.
    • If maxHeap.size > k, pop largest quality top and subtract totalQuality -= top.
    • If maxHeap.size === k: calculate candidate cost totalQuality * R and update minCost.

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

Input

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

Workers data.

Min Cost Team

Hire worker 1 (ratio 2.5) and worker 2 (ratio 6.0) -> cost 105.0.

Minimal wage cost.

Output

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.

Key Takeaways
  • 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.