




Sponsored
This approach uses a heap to dynamically maintain workers while iterating over them sorted by wage-to-quality ratio. The goal is to keep the sum of qualities of the selected workers minimal while ensuring all conditions are satisfied. We sort all workers by their wage-to-quality ratio because for each worker, to satisfy both their minimum wage and relative payment constraints, each selected worker must be paid at least this ratio times their quality.
Time Complexity: O(n log n) due to sorting, and O(n log k) for heap operations.
Space Complexity: O(n) for the sorted list of workers or the heap.
1import heapq
2
3class Solution:
4    def mincostToHireWorkers(self, quality, wage, k):
5        workers = sorted((w / q, q) for q, w in zip(quality, wage))
6        result = float('inf')
7        quality_sum = 0
8        heap = []
9
10        for ratio, q in workers:
11            heapq.heappush(heap, -q)
12            quality_sum += q
13
14            if len(heap) > k:
15                quality_sum += heapq.heappop(heap)
16
17            if len(heap) == k:
18                result = min(result, ratio * quality_sum)
19
20        return resultThe solution begins by sorting each worker by their wage-to-quality ratio. It then uses a max-heap to maintain the k workers with the smallest sum of qualities. For each worker evaluated, we add their quality to the max heap. If the max heap exceeds k in size, we remove the largest quality to ensure we're considering the smallest k qualities. The current cost calculated by multiplying the present worker's rate with the sum of qualities in the heap is considered as a potential minimum.
This approach focuses on sorting workers by the ratio of their wage expectation to quality. By calculating this ratio, we can use it as a reference point to determine the required payment for every possible group of k workers. Selecting the right workers and calculating the minimum payment by understanding proportional wages can be done by iterating over sorted worker lists using two indices, capturing the required details and performing the necessary calculations.
Time Complexity: O(n log n) due to sorting, and O(n log n) due to managing heap.
Space Complexity: O(n) for worker list and heap storage.
Segregating worker efficiency by respective wage-to-quality metrics solidifies the C algorithm, with simplifying sorting. Equally distributing qualities through heap operations, the smallest worker groups reach the optimally minimized cost using prearranged calculations.