1
1
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 ]);
23
11
24
- class Pair {
25
- double x ;
26
- int q ;
12
+ Arrays .sort (workers , (a , b ) -> Double .compare (a .getKey (), b .getKey ()));
27
13
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 );
31
23
}
32
- }
24
+
25
+ return ans ;
26
+ }
27
+ }
0 commit comments