There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example:
Input: quality = [10,20,5], wage = [70,50,30], K = 2 Output: 105.00000 Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Java Solution
First, sort workers by their wage/quality ratio in ascending order. The smaller ratio value means better quality and low wage. Then try the best ratio first and use the heap to track the largest quality. Given a ratio, the largest quality is removed from the queue because it takes more wage.
class Solution { public double mincostToHireWorkers(int[] quality, int[] wage, int K) { ArrayList<Worker> list = new ArrayList<>(); for(int i=0; i<wage.length; i++){ list.add(new Worker(quality[i], wage[i])); } Comparator<Worker> comp = Comparator.comparing((Worker w) -> w.ratio); Collections.sort(list, comp); PriorityQueue<Integer> q = new PriorityQueue<>(); int sum = 0; double result = Integer.MAX_VALUE; for(int i=0; i<list.size(); i++){ Worker w = list.get(i); sum += w.quality; q.offer(-w.quality); if(q.size()>K){ int extra = q.poll(); sum += extra; } if(q.size() == K){ result = Math.min(result, sum * w.ratio); } } return result; } } class Worker{ int quality; int wage; double ratio; public Worker(int q, int w){ this.quality = q; this.wage = w; this.ratio = (double)w/q; } } |