There are N
workers. The i
-th worker has a quality[i]
and a minimum wage expectation wage[i]
.
Now we want to hire exactly K
workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
- Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
- Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2 Output: 105.00000 Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3 Output: 30.66667 Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000
, whereN = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
- Answers within
10^-5
of the correct answer will be considered correct.
思路:最开始以为二分,后来发现暴力复杂度都是更低的,所以得另寻它法,
注意到我们需要小的W/Q比,而且所有人这个比值是一样的,但是假定我们选了k个人,最后给他们的开的W/Q又一定是k个人中最大的,不然有的人就满足不了最小的wage,所以W/Q是由大的数值主导。
这样的话,就可以先对W/Q排序,这样W/Q值就是最后选的那个人,然后只要求Q总和最小的k个就好,于是sort+PriorityQueue
import heapq
class Solution:
def mincostToHireWorkers(self, q, w, k):
"""
:type quality: List[int]
:type wage: List[int]
:type K: int
:rtype: float
"""
a=[(j/i,i,j) for i,j in zip(q,w)]
a.sort()
pq = [-t[1] for t in a[:k]]
totalQ = sum([-t for t in pq])
mi = totalQ*a[k-1][0]
heapq.heapify(pq)
for i in range(k,len(q)):
totalQ -= -heapq.heappop(pq)
totalQ += a[i][1]
heapq.heappush(pq, -a[i][1])
mi = min(mi, totalQ*a[i][0])
return mi
s=Solution()
print(s.mincostToHireWorkers(q = [10,20,5], w = [70,50,30], k = 2))
print(s.mincostToHireWorkers(q = [3,1,10,10,1], w = [4,8,2,2,7], k = 3))