LeetCode 857. Minimum Cost to Hire K Workers

原题链接在这里:https://leetcode.com/problems/minimum-cost-to-hire-k-workers/description/

题目:

There are n workers. You are given two integer arrays quality and wage where quality[i] is the quality of the ith worker and wage[i] is the minimum wage expectation for the ith worker.

We want to hire exactly k workers to form a paid group. To hire a group of k workers, we must pay them according to the following rules:

  1. Every worker in the paid group must be paid at least their minimum wage expectation.
  2. In the group, each worker's pay must be directly proportional to their quality. This means if a worker’s quality is double that of another worker in the group, then they must be paid twice as much as the other worker.

Given the integer k, return the least amount of money needed to form a paid group satisfying the above conditions. Answers within 10-5 of the actual answer will be accepted.

Example 1:

Input: quality = [10,20,5], wage = [70,50,30], k = 2
Output: 105.00000
Explanation: We pay 70 to 0th worker and 35 to 2nd 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 0th worker, 13.33333 to 2nd and 3rd workers separately. 

Constraints:

  • n == quality.length == wage.length
  • 1 <= k <= n <= 104
  • 1 <= quality[i], wage[i] <= 104

题解:

There are two rules. one is the pay the minimum wage expectation. the second is to pay the same ratio for the group.

Thus we want to have a relatively smaller ratio.

We first sort based on ratio. The kth ratio is a starting candidate for total cost.
But quality may be to high, thus we want to try the next candidate, ratio may be higher, but total quality may be lower.

To exclude the highest quality, we maintain a maxHeap.

Time Complexity: O(nlogn). n = quality.length.

Space: O(n).

AC Java:

 1 class Solution {
 2     public double mincostToHireWorkers(int[] quality, int[] wage, int k) {
 3         int n = quality.length;
 4         double[][] worker = new double[n][2];
 5         for(int i = 0; i < n; i++){
 6             worker[i] = new double[]{(double)wage[i] / quality[i], quality[i]};
 7         }
 8 
 9         Arrays.sort(worker, (a, b) -> Double.compare(a[0], b[0]));
10         double res = Double.MAX_VALUE;
11         PriorityQueue<Double> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
12         double countSum = 0;
13         for(double[] w : worker){
14             countSum += w[1];
15             maxHeap.add(w[1]);
16             if(maxHeap.size() > k){
17                 countSum -= maxHeap.poll();
18             }
19 
20             if(maxHeap.size() == k){
21                 res = Math.min(res, countSum * w[0]);
22             }
23         }
24 
25         return res;
26     }
27 }

类似Maximum Performance of a Team.

posted @ 2024-07-02 11:03  Dylan_Java_NYC  阅读(9)  评论(0编辑  收藏  举报