|
2 | 2 |
|
3 | 3 | import io.github.spannm.leetcode.LeetcodeProblem;
|
4 | 4 |
|
5 |
| -import java.util.Arrays; |
6 |
| -import java.util.Comparator; |
7 | 5 | import java.util.PriorityQueue;
|
| 6 | +import java.util.Queue; |
| 7 | +import java.util.stream.IntStream; |
8 | 8 |
|
9 | 9 | /**
|
10 | 10 | * 857. Minimum Cost to Hire K Workers.
|
11 | 11 | */
|
12 | 12 | class Problem0857 extends LeetcodeProblem {
|
13 | 13 |
|
14 | 14 | double mincostToHireWorkers(int[] _quality, int[] _wage, int _k) {
|
15 |
| - int n = _quality.length; |
16 |
| - Pair[] t = new Pair[n]; |
17 |
| - for (int i = 0; i < n; i++) { |
18 |
| - t[i] = new Pair(_quality[i], _wage[i]); |
19 |
| - } |
20 |
| - Arrays.sort(t, Comparator.comparingDouble(a -> a.x)); |
21 |
| - PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a); |
22 |
| - double ans = 1e9; |
| 15 | + Worker[] workers = IntStream.range(0, _quality.length) |
| 16 | + .mapToObj(i -> new Worker(_quality[i], _wage[i])) |
| 17 | + .sorted((_w1, _w2) -> Double.compare(_w1.wagePerQ, _w2.wagePerQ)) |
| 18 | + .toArray(Worker[]::new); |
| 19 | + Queue<Integer> pq = new PriorityQueue<>((a, b) -> b - a); |
| 20 | + double amt = 1e9; |
23 | 21 | int tot = 0;
|
24 |
| - for (var e : t) { |
25 |
| - tot += e.q; |
26 |
| - pq.offer(e.q); |
| 22 | + for (var w : workers) { |
| 23 | + tot += w.quality; |
| 24 | + pq.offer(w.quality); |
27 | 25 | if (pq.size() == _k) {
|
28 |
| - ans = Math.min(ans, tot * e.x); |
| 26 | + amt = Math.min(amt, tot * w.wagePerQ); |
29 | 27 | tot -= pq.poll();
|
30 | 28 | }
|
31 | 29 | }
|
32 |
| - return ans; |
| 30 | + return amt; |
33 | 31 | }
|
34 | 32 |
|
35 |
| - static class Pair { |
36 |
| - private final double x; |
37 |
| - private final int q; |
| 33 | + static class Worker { |
| 34 | + private final int quality; // quality |
| 35 | + private final double wagePerQ; // wage per quality |
38 | 36 |
|
39 |
| - Pair(int _q, int _w) { |
40 |
| - q = _q; |
41 |
| - x = (double) _w / _q; |
| 37 | + Worker(int _q, int _w) { |
| 38 | + quality = _q; |
| 39 | + wagePerQ = (double) _w / _q; |
42 | 40 | }
|
43 | 41 |
|
44 | 42 | }
|
|
0 commit comments