Minimum Cost to Hire K Workers

Hard

Topics
ArrayGreedySortingHeap

There are n workers. Worker i has quality nums[i] (first n/2 of the array) and minimum wage expectation nums[i] (second n/2). You want to hire exactly target workers. In a paid group, each worker is paid in proportion to their quality relative to the group, and each must receive at least their minimum wage. Return the minimum total cost (integer part) to hire exactly target workers.

Encoding: nums has 2k elements: first k are qualities, next k are wages. target is the number to hire.

Example 1

10020152703504305
Input:  nums = [10,20,5,70,50,30], target = 2
Output: 105

Example 2

30111021031415
Input:  nums = [3,1,10,10,1,1], target = 2
Output: 11
Explanation: quality = [3,1,10], wage = [10,1,1]. Hiring workers 1 and 2 needs a rate of max(1/1, 1/10) = 1.0, so the cost is 1.0 * (1+10) = 11. The other pairs cost 13.3 and 43.3.

Constraints

  • 2 <= n <= 50 (n = nums.length / 2)
  • 1 <= target <= n
  • 1 <= quality[i], wage[i] <= 10^4
Editorial — intuition, approach, complexity and pitfalls

Intuition

Within a paid group every worker is paid in proportion to quality, so one number — the group's pay rate per unit of quality — determines everyone's wage. Each worker i demands at least wage[i], which means the rate must be at least wage[i] / quality[i]. So the group's rate is the maximum ratio among its members, and the total cost is rate × sum of qualities.

That factorisation is the whole solution. Sort the workers by ratio and sweep: when worker i is considered, every worker before them has a ratio no larger, so i's ratio is the rate for any group drawn from the prefix. Minimising cost at that fixed rate means minimising the sum of qualities, so keep the k smallest qualities seen so far — which a max-heap of size k does by evicting its largest.

Approach

  1. Split the encoded array into qualities and wages, and sort worker indices by wage / quality.
  2. Sweep in that order, pushing each quality onto a max-heap and accumulating the total.
  3. When the heap exceeds target, pop the largest quality and subtract it.
  4. Whenever the heap holds exactly target workers, the candidate cost is ratio × totalQuality; keep the smallest.

Dry Run

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

ratios   70/10 = 7.0    50/20 = 2.5    30/5 = 6.0
sorted by ratio: worker 1 (2.5), worker 2 (6.0), worker 0 (7.0)

  worker  ratio  heap of qualities  total  group size  cost
  1       2.5    [20]               20     1           --
  2       6.0    [20, 5]            25     2           6.0 * 25 = 150
  0       7.0    [20, 10] after
                 evicting 5? no --
                 push 10, total 35,
                 evict the largest 20
                 -> [10, 5] total 15  2     7.0 * 15 = 105

answer 105

note that the cheapest group is NOT the two lowest ratios: worker 0 has the
highest ratio but the group {0, 2} has the smallest quality sum.

Complexity

  • Time — O(n log n): the sort dominates; the heap does O(n) pushes and pops of O(log k) each.
  • Space — O(n) for the sorted index list and the heap.

Common Pitfalls

  • Picking the k workers with the smallest ratios. The dry run is the counterexample: the winning group includes the worker with the highest ratio, because quality sum matters as much as rate.
  • Picking the k smallest qualities outright, ignoring ratios. The rate is then set by whichever of them is most expensive, which may be far worse.
  • Using a min-heap. You need to evict the largest quality to keep the sum small, which is a max-heap operation.
  • Recomputing the group cost from scratch each step instead of maintaining the running sum, which turns O(n log n) into O(n k).
  • Comparing ratios with floating point and then computing the cost in floating point too. Sorting by wage/quality as a double is standard and safe at these bounds; the shown code then computes the cost as wage[i] * total / quality[i] in integers, which avoids accumulating rounding error in the number actually returned.
  • Taking the integer part of each candidate and then the minimum, and worrying that it differs from the minimum of the exact costs. It does not — flooring is monotone, so it commutes with taking a minimum.

Full Solution — all languages

class Solution:
    def mincostToHireWorkers(self, nums, target):
        import heapq
        half = len(nums) // 2
        quality = nums[:half]
        wage = nums[half:]
        workers = sorted(range(half), key=lambda i: wage[i] / quality[i])
        heap = []
        total_quality = 0
        best = None
        for i in workers:
            heapq.heappush(heap, -quality[i])
            total_quality += quality[i]
            if len(heap) > target:
                total_quality += heapq.heappop(heap)
            if len(heap) == target:
                # exact: wage[i] / quality[i] is the group's rate
                cost = wage[i] * total_quality // quality[i]
                best = cost if best is None else min(best, cost)
        return 0 if best is None else best
SensAI
Beta
Tap the mic to stop voice mode