Minimum Cost to Hire K Workers
Hard
Topics
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
Input: nums = [10,20,5,70,50,30], target = 2 Output: 105
Example 2
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
- Split the encoded array into qualities and wages, and sort worker indices by
wage / quality. - Sweep in that order, pushing each quality onto a max-heap and accumulating the total.
- When the heap exceeds
target, pop the largest quality and subtract it. - Whenever the heap holds exactly
targetworkers, the candidate cost isratio × 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
kworkers 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
ksmallest 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/qualityas a double is standard and safe at these bounds; the shown code then computes the cost aswage[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 bestimport java.util.*;
class Solution {
public int mincostToHireWorkers(int[] nums, int target) {
int half = nums.length / 2;
int[] quality = Arrays.copyOfRange(nums, 0, half);
int[] wage = Arrays.copyOfRange(nums, half, nums.length);
Integer[] order = new Integer[half];
for (int i = 0; i < half; i++) order[i] = i;
Arrays.sort(order, (x, y) -> Long.compare((long) wage[x] * quality[y], (long) wage[y] * quality[x]));
PriorityQueue<Integer> heap = new PriorityQueue<>(Comparator.reverseOrder());
long totalQuality = 0, best = -1;
for (int i : order) {
heap.add(quality[i]);
totalQuality += quality[i];
if (heap.size() > target) totalQuality -= heap.poll();
if (heap.size() == target) {
long cost = (long) wage[i] * totalQuality / quality[i];
if (best < 0 || cost < best) best = cost;
}
}
return (int) (best < 0 ? 0 : best);
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int mincostToHireWorkers(vector<int>& nums, int target) {
int half = nums.size() / 2;
vector<int> quality(nums.begin(), nums.begin() + half);
vector<int> wage(nums.begin() + half, nums.end());
vector<int> order(half);
for (int i = 0; i < half; i++) order[i] = i;
sort(order.begin(), order.end(), [&](int x, int y) {
return (long long)wage[x] * quality[y] < (long long)wage[y] * quality[x];
})
;
priority_queue<int> heap;
long long totalQuality = 0, best = -1;
for (int i : order) {
heap.push(quality[i]);
totalQuality += quality[i];
if ((int)heap.size() > target) {
totalQuality -= heap.top();
heap.pop();
}
if ((int)heap.size() == target) {
long long cost = (long long)wage[i] * totalQuality / quality[i];
if (best < 0 || cost < best) best = cost;
}
}
return (int)(best < 0 ? 0 : best);
}
};/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/ var mincostToHireWorkers = function(nums, target) {
const half = nums.length / 2;
const quality = nums.slice(0, half), wage = nums.slice(half);
const order = Array.from({ length: half }, (_, i) => i) .sort((x, y) => wage[x] / quality[x] - wage[y] / quality[y]);
// Small inputs here, so a kept-sorted list of chosen qualities stands in
// for the max-heap that makes this scale.
const chosen = [];
let totalQuality = 0, best = null;
for (const i of order) {
let at = 0;
while (at < chosen.length && chosen[at] < quality[i]) at++;
chosen.splice(at, 0, quality[i]);
totalQuality += quality[i];
if (chosen.length > target) totalQuality -= chosen.pop();
if (chosen.length === target) {
const cost = Math.floor(wage[i] * totalQuality / quality[i]);
best = best === null ? cost : Math.min(best, cost);
}
}
return best === null ? 0 : best;
};