LeetCode 857. Minimum Cost to Hire K Workers DP坑 反直觉

本文探讨了一种算法问题,即如何以最小的成本雇佣K名工人,每位工人的支付需按其质量比例分配,并且不低于其最低工资期望。通过分析价格性能比,提出了一种排序并选择最优价格性能比工人的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

---------------------------------------------------------------------------------------------

First, I wrote a DP codes. However, if using dp[i][j] to stand the picked out i workers ending with j, the dp recursive formula is actually not right. 

The key points for this problem is to understand the price-performanceratio. Generally, we use performance-price ratio and the customers pursue higher performance-price ratio. As opposed to performance-price ratio, workers prefer higher price-performance ratio. The highest price-performance ratio is suitable for all workers. So we sort by price-perfermance ratio first and pick out K workers with <=  some price-perfermance ratio and the least quality.

import heapq

class Solution:
    def mincostToHireWorkers(self, quality, wage, K: int) -> float:
        l = len(quality)
        ratio_arr = sorted([(wage[i] / quality[i], i) for i in range(l)])
        heap, sumq, res = [], 0, float('inf')

        for ratio, idx in ratio_arr:
            sumq += quality[idx]
            heapq.heappush(heap, -quality[idx])
            if (len(heap) > K):
                sumq += heapq.heappop(heap)
            if (len(heap) == K):
                res = min(res, sumq * ratio)
        return res

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值