题目地址:
https://www.lintcode.com/problem/1512/
给定 n n n个工人,其有两个属性,一个是质量,一个是期望工资,以长 n n n数组 q q q和 w w w表示。给定一个正整数 k , k ≤ n k,k\le n k,k≤n,要求雇佣恰好 k k k名工人,使得这 k k k个工人,每个工人的薪资与其 q q q值成比例,并且每个工人的薪资不低于其期望薪资。问满足条件的情况下,最少总共要付多少薪资。
参考https://blog.csdn.net/qq_46105170/article/details/119380604。代码如下:
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
public class Solution {
/**
* @param quality: an array
* @param wage: an array
* @param K: an integer
* @return: the least amount of money needed to form a paid group
*/
public double mincostToHireWorkers(int[] quality, int[] wage, int K) {
// Write your code here
List<double[]> list = new ArrayList<>();
for (int i = 0; i < quality.length; i++) {
list.add(new double[]{quality[i], wage[i]});
}
list.sort((w1, w2) -> Double.compare(w1[1] / w1[0], w2[1] / w2[0]));
double res = 1e18, sum = 0.0;
PriorityQueue<Double> minHeap = new PriorityQueue<>((x, y) -> -Double.compare(x, y));
for (double[] w : list) {
sum += w[0];
minHeap.offer(w[0]);
if (minHeap.size() > K) {
sum -= minHeap.poll();
}
if (minHeap.size() == K) {
res = Math.min(res, w[1] / w[0] * sum);
}
}
return res;
}
}
时间复杂度 O ( n log n ) O(n\log n) O(nlogn),空间 O ( k ) O(k) O(k)。