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

时间:2023-12-16 14:27:02

2018-10-06 20:17:30

问题描述:

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

问题求解:

问题规模是10000,已经基本说明是O(nlogn)复杂度的算法,这个复杂度最常见的就是排序算法了,本题确实是使用排序算法来进行进行求解。

本题中指出最后支付的费用和工人的quality相关,也就是说

paid[i] : quality[i] = paid[j] : quality[j] = ratio(固定值)

换言之我们可以按照wage[i] / quality[i]来进行排序,另外还需要维护一个优先队列,大小为K,在超过K之后需要将quality最大的数进行排除。

    public double mincostToHireWorkers(int[] quality, int[] wage, int K) {
double res = Double.MAX_VALUE;
int n = quality.length;
double[][] workers = new double[n][2];
for (int i = 0; i < n; i++) {
workers[i][0] = wage[i] * 1.0 / quality[i];
workers[i][1] = quality[i];
}
Arrays.sort(workers, new Comparator<double[]>() {
@Override
public int compare(double[] o1, double[] o2) {
return Double.compare(o1[0], o2[0]);
}
});
PriorityQueue<Double> pq = new PriorityQueue<>();
double curSum = 0;
for (double[] worker : workers) {
curSum += worker[1];
pq.add(-worker[1]);
if (pq.size() > K) curSum += pq.poll();
if (pq.size() == K) res = Math.min(res, curSum * worker[0]);
}
return res;
}