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:

  1. Input: quality = [10,20,5], wage = [70,50,30], K = 2
  2. Output: 105.00000
  3. Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.

Example 2:

  1. Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
  2. Output: 30.66667
  3. 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.

有N个工人,第i个工人的质量是quality[i],最小工资期盼是wage[i],现在想雇K个工人组成一个支付组,返回所需的最小花费。有两个条件:

1. K个工人的质量和给他开的工资的比例是相同的。
2. 每个工人都要满足他的最小期望工资。

解法:最大堆, heapq, PriorityQueue。首先对付工资和质量的比率进行排序wage/quality,同时记录quality,也就是(wage/quality, quality),代表一个工人情况,比率越大说明工人效率越低。选定的K个人最后要按照相同的比率来支付工资,为了保证每个人的最低工资标准,只能选定比率最高的人的比率来支付工资。每个人的支付工资:wage = ratio * quality,总的支付工资:total wage = ratio * total quality,在ratio相同的情况小,总的quality越小越好。用一个变量result记录最小花费,初始为最大浮点数。循环排序好的工资比率,用一个变量qsum累加quality,用一个最大堆记录当前的quality,堆顶是最大的quality,如果堆长度等于K+1,就弹出quality最大的,同时qsum中去掉这个最大值。堆满足K个工人的时候,每次都计算qsum * ratio,和result比较取小的。

Java:

  1. public double mincostToHireWorkers(int[] q, int[] w, int K) {
  2. double[][] workers = new double[q.length][2];
  3. for (int i = 0; i < q.length; ++i)
  4. workers[i] = new double[]{(double)(w[i]) / q[i], (double)q[i]};
  5. Arrays.sort(workers, (a, b) -> Double.compare(a[0], b[0]));
  6. double res = Double.MAX_VALUE, qsum = 0;
  7. PriorityQueue<Double> pq = new PriorityQueue<>();
  8. for (double[] worker: workers) {
  9. qsum += worker[1];
  10. pq.add(-worker[1]);
  11. if (pq.size() > K) qsum += pq.poll();
  12. if (pq.size() == K) res = Math.min(res, qsum * worker[0]);
  13. }
  14. return res;
  15. }  

Python:

  1. def mincostToHireWorkers(self, quality, wage, K):
  2. workers = sorted([float(w) / q, q] for w, q in zip(wage, quality))
  3. res = float('inf')
  4. qsum = 0
  5. heap = []
  6. for r, q in workers:
  7. heapq.heappush(heap, -q)
  8. qsum += q
  9. if len(heap) > K: qsum += heapq.heappop(heap)
  10. if len(heap) == K: res = min(res, qsum * r)
  11. return res

Python:

  1. # Time: O(nlogn)
  2. # Space : O(n)
  3.  
  4. import itertools
  5. import heapq
  6.  
  7. class Solution(object):
  8. def mincostToHireWorkers(self, quality, wage, K):
  9. """
  10. :type quality: List[int]
  11. :type wage: List[int]
  12. :type K: int
  13. :rtype: float
  14. """
  15. workers = [[float(w)/q, q] for w, q in itertools.izip(wage, quality)]
  16. workers.sort()
  17. result = float("inf")
  18. qsum = 0
  19. max_heap = []
  20. for r, q in workers:
  21. qsum += q
  22. heapq.heappush(max_heap, -q)
  23. if len(max_heap) > K:
  24. qsum -= -heapq.heappop(max_heap)
  25. if len(max_heap) == K:
  26. result = min(result, qsum*r)
  27. return result  

Python: O(nlogn) time,O(n) space

  1. class Solution(object):
  2. def mincostToHireWorkers(self, quality, wage, K):
  3. """
  4. :type quality: List[int]
  5. :type wage: List[int]
  6. :type K: int
  7. :rtype: float
  8. """
  9. # 按比例排序,nlogn
  10. workers = sorted([float(wage[i])/quality[i], quality[i]] for i in range(len(quality)))
  11. res,qsum = float('inf'),0
  12. heap = []
  13.  
  14. for i in range(len(workers)):
  15. # 选定比例 r
  16. r,q = workers[i]
  17. heapq.heappush(heap,-q)
  18. # qsum始终记录k个人的quality之和,乘以r即为最后结果
  19. qsum += q
  20. if len(heap) > K:
  21. # 始终丢弃quality最大的人
  22. qsum += heapq.heappop(heap)
  23. if len(heap) == K:
  24. res = min(res, qsum * r)
  25. return res

C++:

  1. double mincostToHireWorkers(vector<int> q, vector<int> w, int K) {
  2. vector<vector<double>> workers;
  3. for (int i = 0; i < q.size(); ++i)
  4. workers.push_back({(double)(w[i]) / q[i], (double)q[i]});
  5. sort(workers.begin(), workers.end());
  6. double res = DBL_MAX, qsum = 0;
  7. priority_queue<int> pq;
  8. for (auto worker: workers) {
  9. qsum += worker[1], pq.push(worker[1]);
  10. if (pq.size() > K) qsum -= pq.top(), pq.pop();
  11. if (pq.size() == K) res = min(res, qsum * worker[0]);
  12. }
  13. return res;
  14. }

C++:

  1. // Time: O(nlogn)
  2. // Space: O(n)
  3. class Solution {
  4. public:
  5. double mincostToHireWorkers(vector<int>& quality, vector<int>& wage, int K) {
  6. vector<pair<double, int>> workers;
  7. for (int i = 0; i < quality.size(); ++i) {
  8. workers.emplace_back(static_cast<double>(wage[i]) / quality[i],
  9. quality[i]);
  10. }
  11. sort(workers.begin(), workers.end());
  12. auto result = numeric_limits<double>::max();
  13. auto sum = 0.0;
  14. priority_queue<int> max_heap;
  15. for (const auto& worker: workers) {
  16. sum += worker.second;
  17. max_heap.emplace(worker.second);
  18. if (max_heap.size() > K) {
  19. sum -= max_heap.top(), max_heap.pop();
  20. }
  21. if (max_heap.size() == K) {
  22. result = min(result, sum * worker.first);
  23. }
  24. }
  25. return result;
  26. }
  27. };

  

All LeetCode Questions List 题目汇总

[LeetCode] 857. Minimum Cost to Hire K Workers 雇K个工人的最小花费的更多相关文章

  1. [LeetCode] 857. Minimum Cost to Hire K Workers 雇佣K名工人的最低成本

    There are N workers.  The i-th worker has a quality[i] and a minimum wage expectation wage[i]. Now w ...

  2. 【LeetCode】857. Minimum Cost to Hire K Workers 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/minimum- ...

  3. 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 w ...

  4. [Swift]LeetCode857. 雇佣 K 名工人的最低成本 | 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 w ...

  5. LeetCode 1000. Minimum Cost to Merge Stones

    原题链接在这里:https://leetcode.com/problems/minimum-cost-to-merge-stones/ 题目: There are N piles of stones ...

  6. LeetCode 1130. Minimum Cost Tree From Leaf Values

    原题链接在这里:https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/ 题目: Given an array arr of ...

  7. LeetCode 983. Minimum Cost For Tickets

    原题链接在这里:https://leetcode.com/problems/minimum-cost-for-tickets/ 题目: In a country popular for train t ...

  8. 雇佣K个工人的最小费用 Minimum Cost to Hire K Workers

    2018-10-06 20:17:30 问题描述: 问题求解: 问题规模是10000,已经基本说明是O(nlogn)复杂度的算法,这个复杂度最常见的就是排序算法了,本题确实是使用排序算法来进行进行求解 ...

  9. [LeetCode] 712. Minimum ASCII Delete Sum for Two Strings 两个字符串的最小ASCII删除和

    Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal. ...

随机推荐

  1. 一加5安卓P刷入twrp的recovery

    本文介绍的方法属于普适性的一般方法,比网上的各种工具箱会繁琐.但是工具箱不一定一直会更新(之前一加论坛的刷机工具箱已经停止更新了,估计是作者不用一加5了吧,毕竟已经好几年的手机了).并且如果你手机更新 ...

  2. WebKit应用程序开发的起因

    公司的Web管理界面,用起来还可以,但是有一个问题一直无法解决. 在web页面上需要播放视频,由于比较这个功能比较老,不支持web模式播放,只支持CS模式,具体原因及不说了. 于是有了 winform ...

  3. 算法图解(python3版本)--读后感

    本想写详细点,但入门书籍没啥干货,一天就看完了,简单介绍下: 大纲--两方面 一.介绍算法是什么:算法的作用,判断算法效率高低的指标 ①通过编程解决问题的思路,或者说程序本身就是算法,算法作用是为了提 ...

  4. 修改idea,webstrom,phpstrom 快捷键double shift 弹出search everywhere

    这个问题很困惑,因为这个功能很好用,查找什么很方便,but! 我用了十年的搜狗输入法,大家都知道搜狗输入法按shift中英文切换很方便,特别在写代码时候...所以就和这个double shift功能冲 ...

  5. EF实体类指定部分属性不映射数据库标记

    命名空间 ;using System.ComponentModel.DataAnnotations.Schema; 实体部分 public partial class Student { [NotMa ...

  6. [Javascript] Sort by multi factors

    For example, we have a 2D arrays; const arys = [ [], [], [] ]; We want to sort by the number first, ...

  7. LeetCode 439. Ternary Expression Parser

    原题链接在这里:https://leetcode.com/problems/ternary-expression-parser/description/ 题目: Given a string repr ...

  8. BZOJ 4103: [Thu Summer Camp 2015]异或运算 可持久化trie

    开始想了一个二分+可持久化trie验证,比正解多一个 log 仔细思考,你发现你可以直接按位枚举,然后在可持久化 trie 上二分就好了. code: #include <bits/stdc++ ...

  9. Lightning Web Components 组件生命周期(六)

    组件创建以及渲染流程 组件移除dom 处理流程 组件从dom 移除 组件中的disconnectedCallback() 方法被调用 子组件从dom 移除 每个子组件的disconnectedCall ...

  10. Element源码---初识框架

    序言 如果前期直接看源码,你会发现源码越看越看不懂,越看越难,觉得没有办法入手去写,其实首先想要了解项目结构最简单的方法就是通过目录 1.项目理念 2.解析目录 目前想不到更好的办法整理element ...