1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Solution { public double mincostToHireWorkers(int[] quality, int[] wage, int k) { int n = quality.length, sum = 0; Integer[] index = IntStream.range(0, n).boxed().toArray(Integer[]::new);
Arrays.sort(index, (a, b) -> wage[a] * quality[b] - wage[b] * quality[a]); PriorityQueue<Integer> q = new PriorityQueue<>((a, b) -> b - a); for (int i = 0; i < k; ++i) { q.offer(quality[index[i]]); sum += quality[index[i]]; } double ans = sum * ((double) wage[index[k - 1]] / quality[index[k - 1]]); for (int i = k; i < n; ++i) { int cur = quality[index[i]]; if (cur < q.peek()) { sum -= q.poll() - cur; q.offer(cur); ans = Math.min(ans, sum * ((double) wage[index[i]] / cur)); } } return ans; } }
|