857. Minimum Cost to Hire K Workers

51 篇文章 0 订阅
Description

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, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.

Problem URL


Solution

给一个数组quality表示员工工作质量,wage表示员工能接受的最低工资。问从中雇佣K名员工的最低工资。要求每个员工被支付的工资要和他工作质量成比例,且不能低于他要求的最低工资。
有q1:q2 = w1:w2,所以w1:q1 = w2:q2,所有用功的工资都是满足这样的比例的,而我们像找到最低工资,就可以找到一个合适的最低比例,再乘总quality即可。

Document the ratio of w1:q1 of each workers, then sort it by ratio so we can get the minimal ratio to count sum cost of K workers. Then using a priority queue to maintain k workers who have min ratio. An int qSum is the sum of their quality.

Code
class Solution {
    public double mincostToHireWorkers(int[] quality, int[] wage, int K) {
        double[][] workers = new double[quality.length][2];
        for (int i = 0; i < quality.length; ++i){
            workers[i] = new double[]{(double)(wage[i]) / quality[i], (double)quality[i]};
        }
        Arrays.sort(workers, (a, b) -> Double.compare(a[0], b[0]));
        double res = Double.MAX_VALUE, qSum = 0;
        PriorityQueue<Double> pq = new PriorityQueue<>();
        for (double[] worker : workers){
            qSum += worker[1];
            pq.add(-worker[1]);
            if (pq.size() > K){
                qSum += pq.poll();
            }
            if (pq.size() == K){
                res = Math.min(res, qSum * worker[0]);
            }
        }
        return res;
    }
}

Time Complexity: O(n)
Space Complexity: O(n)


Review

Google always has some facinating problem.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值