Skip to content

Commit 8d78b28

Browse files
authored
Update Solution.java
previous it was giving wrong asnwer, I have tested and the new code works
1 parent eef5794 commit 8d78b28

File tree

1 file changed

+23
-28
lines changed
  • solution/0800-0899/0857.Minimum Cost to Hire K Workers

1 file changed

+23
-28
lines changed
Lines changed: 23 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,27 @@
11
class Solution {
2-
public double mincostToHireWorkers(int[] quality, int[] wage, int k) {
3-
int n = quality.length;
4-
Pair[] t = new Pair[n];
5-
for (int i = 0; i < n; ++i) {
6-
t[i] = new Pair(quality[i], wage[i]);
7-
}
8-
Arrays.sort(t, (a, b) -> Double.compare(a.x, b.x));
9-
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);
10-
double ans = 1e9;
11-
int tot = 0;
12-
for (var e : t) {
13-
tot += e.q;
14-
pq.offer(e.q);
15-
if (pq.size() == k) {
16-
ans = Math.min(ans, tot * e.x);
17-
tot -= pq.poll();
18-
}
19-
}
20-
return ans;
21-
}
22-
}
2+
public double mincostToHireWorkers(int[] quality, int[] wage, int k) {
3+
double ans = Double.MAX_VALUE;
4+
int qualitySum = 0;
5+
// (wagePerQuality, quality) sorted by wagePerQuality
6+
Pair<Double, Integer>[] workers = new Pair[quality.length];
7+
Queue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
8+
9+
for (int i = 0; i < quality.length; ++i)
10+
workers[i] = new Pair<>((double) wage[i] / quality[i], quality[i]);
2311

24-
class Pair {
25-
double x;
26-
int q;
12+
Arrays.sort(workers, (a, b) -> Double.compare(a.getKey(), b.getKey()));
2713

28-
Pair(int q, int w) {
29-
this.q = q;
30-
this.x = (double) w / q;
14+
for (Pair<Double, Integer> worker : workers) {
15+
final double wagePerQuality = worker.getKey();
16+
final int q = worker.getValue();
17+
maxHeap.offer(q);
18+
qualitySum += q;
19+
if (maxHeap.size() > k)
20+
qualitySum -= maxHeap.poll();
21+
if (maxHeap.size() == k)
22+
ans = Math.min(ans, qualitySum * wagePerQuality);
3123
}
32-
}
24+
25+
return ans;
26+
}
27+
}

0 commit comments

Comments
 (0)