857. Minimum Cost to Hire K Workers

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:

  1. Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
  2. 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. 1 <= K <= N <= 10000, where N = quality.length = wage.length
  2. 1 <= quality[i] <= 10000
  3. 1 <= wage[i] <= 10000
  4. 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))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值