Skip to problem
←

Minimum Cost to Hire K Workers

Hard 0 attempts

You're given two arrays, quality and wage, describing a pool of workers, plus a target headcount k. Form a group of exactly k workers while paying as little in total as possible. Within the hired group, pay must stay proportional to each worker's quality score, and no one can be paid less than the minimum wage they listed.

All selected workers must share one pay rate r: worker i receives r × quality[i], which must be at least wage[i]. Payments may be fractional. Return the total cost, not the worker indices or the rate.

For Example 1, hiring workers 0 and 2 at rate 7 pays 70 and 35, totaling 105. Paying each person only their requested wage would not necessarily preserve the required proportions.

Function contract

Implement mincostToHireWorkers(quality, wage, k). Matching indices describe the same worker: quality[i] is their quality and wage[i] their minimum acceptable pay.

Output: Return the minimum total pay for exactly k workers as a number; fractional pay is allowed. Accepted error is at most 0.00001 × max(1, |expected|).

Example 1

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

Example 2

Input
quality = [3,1,10,10,1]
wage = [4,8,2,2,7]
k = 3
Output
30.6666666667
Constraints
  • quality.length == wage.length == n; 1 <= k <= n <= 10^4
  • 1 <= quality[i], wage[i] <= 10^4

Sort by Ratio + Max-Heap

A selected group needs a rate at least as large as every member’s wage/quality ratio. Sort workers by that ratio. At each rate, all workers seen so far are affordable; retain the k smallest qualities using a max-heap, removing the largest quality when necessary. Their sum multiplied by the current rate is a feasible total. The optimal group is considered when its largest required ratio is reached.

javascript
function mincostToHireWorkers(quality, wage, k) {
  const workers = quality.map((q,i) => [wage[i]/q, q]).sort((a,b) => a[0]-b[0]);

  const heap = [];
  function push(value) {
    heap.push(value); let i = heap.length - 1;
    while (i > 0) {
      const p = Math.floor((i-1)/2); if (heap[p] >= heap[i]) break;
      [heap[p],heap[i]] = [heap[i],heap[p]]; i = p;
    }
  }
  function pop() {
    const max = heap[0], last = heap.pop();
    if (heap.length) {
      heap[0] = last; let i = 0;
      while (2*i+1 < heap.length) {
        let child = 2*i+1;
        if (child+1 < heap.length && heap[child+1] > heap[child]) child++;
        if (heap[i] >= heap[child]) break;
        [heap[i],heap[child]] = [heap[child],heap[i]]; i = child;
      }
    }
    return max;
  }
  let qualSum = 0, min = Infinity;
  for (const [ratio, q] of workers) {
    push(q); qualSum += q;
    if (heap.length > k) { qualSum -= pop(); }
    if (heap.length === k) min = Math.min(min, qualSum * ratio);
  }
  return min;
}

Time: O(n log n) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript