Minimum Cost to Hire K Workers - Problem
You're running a company and need to hire exactly k workers from a pool of n candidates. Each worker has a quality rating and a minimum wage expectation.
Here's the challenge: You must follow these strict hiring rules:
- ๐ Rule 1: Every hired worker must receive at least their minimum wage expectation
- โ๏ธ Rule 2: All workers' pay must be proportional to their quality - if Worker A has twice the quality of Worker B, they must be paid exactly twice as much
Given arrays quality[i] and wage[i] representing each worker's quality and minimum wage expectation, find the minimum total cost to hire exactly k workers while satisfying both rules.
Example: If you hire workers with qualities [3, 1, 2] and they need wages [4, 8, 2], you might pay them [12, 4, 8] respectively (proportional to quality 3:1:2) while meeting everyone's minimum wage.
Input & Output
example_1.py โ Basic Case
$
Input:
quality = [10,20,5], wage = [70,50,30], k = 2
โบ
Output:
105.00000
๐ก Note:
We hire workers 0 and 2. Worker 0: ratio = 70/10 = 7.0, Worker 2: ratio = 30/5 = 6.0. The max ratio is 7.0, so we pay 7.0 ร (10+5) = 105.0 total.
example_2.py โ Equal Ratios
$
Input:
quality = [3,1,10,10,1], wage = [4,8,2,2,7], k = 3
โบ
Output:
30.66667
๐ก Note:
We hire workers with qualities [3,1,10] and ratios [4/3, 8/1, 2/10]. The max ratio is 8.0, so total cost is 8.0 ร (3+1+10)/3 = 30.67.
example_3.py โ Edge Case k=1
$
Input:
quality = [2,3,5], wage = [10,15,20], k = 1
โบ
Output:
10.00000
๐ก Note:
When k=1, we simply choose the worker with minimum wage since there's no proportional constraint with other workers. Worker 0 costs 10.
Constraints
- n == quality.length == wage.length
- 1 โค k โค n โค 104
- 1 โค quality[i], wage[i] โค 104
- All workers must be paid proportionally to their quality
Visualization
Tap to expand
Understanding the Visualization
1
Calculate Ratios
For each worker, calculate their wage-to-quality ratio (their 'price per unit of work')
2
Sort by Efficiency
Sort workers by their ratio - those with lower ratios are more 'cost-efficient'
3
Sliding Window
Process workers in order, maintaining a group of k workers with lowest total quality
4
Heap Optimization
Use max heap to efficiently track and remove highest quality workers when needed
5
Cost Calculation
For each valid group, calculate cost as max_ratio ร total_quality
Key Takeaway
๐ฏ Key Insight: The worker with the highest wage-to-quality ratio in any hired group determines everyone's pay rate. By processing workers in order of increasing ratio and using a heap to maintain the k lowest-quality workers, we efficiently find the optimal hiring combination.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code