LeetCode #857 Hard

Minimum Cost to Hire K Workers

Minimum Cost to Hire K Workers is LeetCode 857 (Hard). Worker i has a quality[i] and a minimum wage wage[i]. You must hire exactly k workers, and their pay must follow two rules:

  • Everyone in the group is paid the same amount per unit of quality, so pay is proportional to quality.
  • Nobody is paid less than their minimum wage.

Return the least total pay for a group of k workers. Answers within 10⁻⁵ of the true value are accepted. With up to 10,000 workers, trying every group of k is out of the question.

Constraints
  • n == quality.length == wage.length
  • 1 <= k <= n <= 10⁴
  • 1 <= quality[i], wage[i] <= 10⁴
arraygreedysortingheap
Open on LeetCode ↗
02

Intuition

Give each worker a rate: wage / quality, the pay per unit of quality they insist on. A group's shared rate has to satisfy its most demanding member, so it is the group's highest rate, and the bill is highest rate × total quality.

Now fix which worker sets the rate. Sort workers by rate. If worker i has the highest rate in the group, the other k - 1 members come from the workers before i in that order, and the cheapest choice is the ones with the smallest quality. A max-heap keeps the k smallest qualities seen so far: add each new worker, and when the heap holds too many, remove the largest quality.

How to spot this pattern

"Choose k items; the cost is one item's maximum of something times the sum of something else" is sort-by-the-first, heap-on-the-second. Maximum Performance of a Team (LeetCode 1383) and Maximum Subsequence Score (LeetCode 2542) use the same pattern with a minimum instead of a maximum.

03

Approach

Try it first

Before reading on, work out what one group of k workers costs, in terms of their rates and qualities. Then ask: if you knew which worker sets the rate, which other workers would you pick? Aim for O(n log n).

1

Sort workers by rate

Pair each quality with its wage and sort by wage / quality. Walking in this order, the worker just added always has the highest rate seen so far, so that worker sets the pay for any group drawn from the workers seen.

2

Add the worker's quality to the group

Push the quality onto a max-heap and add it to total. The heap holds the candidate group, and total is the group's combined quality.

3

Remove the largest quality when the group is too big

If the heap now holds k + 1 workers, pop the largest quality and subtract it from total. Removing the largest quality lowers the bill the most, and the remaining workers' rates are still covered.

4

Price the group

Once the heap holds exactly k workers, the cost is total × rate of the current worker. Keep the smallest cost seen; after the last worker it is the answer.

04

Code in Python, C++ and Java

▶1import heapq
▶2 
▶3class Solution:
▶4 def mincostToHireWorkers(self, quality, wage, k):
▶5 workers = sorted(zip(quality, wage), key=lambda w: w[1] / w[0])
▶6 heap = []
▶7 total = 0
▶8 best = float("inf")
▶9 for q, w in workers:
▶10 heapq.heappush(heap, -q)
▶11 total += q
▶12 if len(heap) > k:
▶13 largest = -heapq.heappop(heap)
▶14 total -= largest
▶15 if len(heap) == k:
▶16 best = min(best, total * w / q)
▶17 return best
workers as givenrate = wage ÷ quality7q 10 · $702.5q 20 · $506q 5 · $30group: largest quality firsttotal quality0qualitytop ratecostbest so farhire 2 of 3 workers
k2
Each card shows a worker's rate, the pay per unit of quality they need, with their quality and minimum wage under it. Everyone in a group is paid at one shared rate, so the group's highest rate sets the price.
workers by rate, low to highrate = wage ÷ quality2.5q 20 · $506q 5 · $307q 10 · $70group: largest quality firsttotal quality0qualitytop ratecostbest so farsorted: lowest rate first
rates[2.5, 6, 7]
In this order, the worker just reached always has the highest rate seen so far. So when worker i joins, worker i sets the rate for any group picked from the first i workers.
workers by rate, low to highrate = wage ÷ quality2.5q 20 · $506q 5 · $307q 10 · $70group: largest quality first20total quality20qualitytop ratecostbest so faradd quality 20 → group of 1
heap[20]max on top
total20
This worker's rate, 2.5, is the highest so far, so they join the group and set its rate. Their quality 20 is added to the total, which becomes 20.
workers by rate, low to highrate = wage ÷ quality2.5q 20 · $506q 5 · $307q 10 · $70group: largest quality first205total quality25qualitytop ratecostbest so faradd quality 5 → group of 2
heap[20, 5]max on top
total25
This worker's rate, 6, is the highest so far, so they join the group and set its rate. Their quality 5 is added to the total, which becomes 25.
workers by rate, low to highrate = wage ÷ quality2.5q 20 · $506q 5 · $307q 10 · $70group: largest quality first205total quality25qualitytop ratecostbest so far25×6=150150group costs 150, new best
cost15025 × 6
best150
The group now has exactly 2 workers with total quality 25. Paying everyone the top rate 6 costs 150, and nobody is under their minimum because every rate in the group is 6 or less. That is the cheapest group so far.
workers by rate, low to highrate = wage ÷ quality2.5q 20 · $506q 5 · $307q 10 · $70group: largest quality first20105total quality35qualitytop ratecostbest so far150add quality 10 → group of 3
heap[20, 10, 5]max on top
total35
This worker's rate, 7, is the highest so far, so they join the group and set its rate. Their quality 10 is added to the total, which becomes 35.
workers by rate, low to highrate = wage ÷ quality2.5q 20 · $506q 5 · $307q 10 · $70group: largest quality first20105total quality35qualitytop ratecostbest so far150too many → remove quality 20
heap[20, 10, 5]size 3 > 2
The group has 3 workers but only 2 can be hired. Removing the largest quality, 20, lowers the total the most.
workers by rate, low to highrate = wage ÷ quality2.5q 20 · $506q 5 · $307q 10 · $70group: largest quality first105total quality15qualitytop ratecostbest so far15×7=105105group costs 105, new best
cost10515 × 7
best105
The group now has exactly 2 workers with total quality 15. Paying everyone the top rate 7 costs 105, and nobody is under their minimum because every rate in the group is 7 or less. That is the cheapest group so far.
workers by rate, low to highrate = wage ÷ quality2.5q 20 · $506q 5 · $307q 10 · $70group: largest quality first105total quality15qualitytop ratecostbest so far105answer: 105
result105.00000
Every worker has had a turn as the rate setter, each time with the smallest qualities available. The cheapest of those prices, 105.00000, is the answer; the green cards are the group that pays it.
05

Common pitfalls

Dividing with integers

✗ Wrong
best = Math.min(best, total * wage[i] / quality[i]);  // all ints
✓ Right
best = Math.min(best, total * ((double) wage[i] / quality[i]));

Integer division throws away the fraction. On quality [3,1,10,10,1], wage [4,8,2,2,7], k = 3 the answer is 30.66667, but the integer version returns 30. In Python, / is already true division; // would make the same mistake.

Removing the smallest quality instead of the largest

✗ Wrong
heapq.heappush(heap, q)
...
total -= heapq.heappop(heap)
✓ Right
heapq.heappush(heap, -q)
...
largest = -heapq.heappop(heap)
total -= largest

Python's heapq is a min-heap, so without the minus sign the pop removes the cheapest worker and keeps the expensive ones. On quality [10,20,5], wage [70,50,30], k = 2 this returns 150 instead of 105.

06

Edge cases

k = 1

One worker is paid exactly their minimum wage, so the answer is the smallest wage. The loop gets there because the heap always keeps the single smallest quality, priced at a rate that covers it.

k = n

Everyone is hired, so the heap first reaches size k at the last worker. That one price, total quality × highest rate, is the answer.

07

Complexity

Time
O(n log n)
Space
O(n)
Sorting takes O(n log n). Each worker is pushed once and popped at most once, at O(log k) each. The sorted list takes O(n) memory and the heap O(k).
08

Minimum Cost to Hire K Workers FAQ

What if the worker just added is the one that gets removed?

Then the heap no longer contains the worker whose rate is used, so that price is too high. It does no harm: the same k workers were in the heap one step earlier, priced at a lower or equal rate, so a cheaper price for this exact group has already been counted.

Why not sort by quality or by wage alone?

Neither tells you who sets the pay rate. A worker with a small wage can still have a very high rate if their quality is tiny, and including them would raise every other member's pay.