|
| 1 | +/** |
| 2 | + * 857. Minimum Cost to Hire K Workers |
| 3 | + * https://leetcode.com/problems/minimum-cost-to-hire-k-workers/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * There are n workers. You are given two integer arrays quality and wage where quality[i] is the |
| 7 | + * quality of the ith worker and wage[i] is the minimum wage expectation for the ith worker. |
| 8 | + * |
| 9 | + * We want to hire exactly k workers to form a paid group. To hire a group of k workers, we must |
| 10 | + * pay them according to the following rules: |
| 11 | + * 1. Every worker in the paid group must be paid at least their minimum wage expectation. |
| 12 | + * 2. In the group, each worker's pay must be directly proportional to their quality. This means |
| 13 | + * if a worker’s quality is double that of another worker in the group, then they must be paid |
| 14 | + * twice as much as the other worker. |
| 15 | + * |
| 16 | + * Given the integer k, return the least amount of money needed to form a paid group satisfying |
| 17 | + * the above conditions. Answers within 10-5 of the actual answer will be accepted. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {number[]} quality |
| 22 | + * @param {number[]} wage |
| 23 | + * @param {number} k |
| 24 | + * @return {number} |
| 25 | + */ |
| 26 | +var mincostToHireWorkers = function(quality, wage, k) { |
| 27 | + const workers = quality.map((q, i) => ({ ratio: wage[i] / q, quality: q })) |
| 28 | + .sort((a, b) => a.ratio - b.ratio); |
| 29 | + |
| 30 | + let result = Infinity; |
| 31 | + let qualitySum = 0; |
| 32 | + const maxHeap = new MaxPriorityQueue(); |
| 33 | + |
| 34 | + for (const worker of workers) { |
| 35 | + maxHeap.enqueue(worker.quality); |
| 36 | + qualitySum += worker.quality; |
| 37 | + |
| 38 | + if (maxHeap.size() > k) { |
| 39 | + qualitySum -= maxHeap.dequeue(); |
| 40 | + } |
| 41 | + |
| 42 | + if (maxHeap.size() === k) { |
| 43 | + result = Math.min(result, qualitySum * worker.ratio); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + return result; |
| 48 | +}; |
0 commit comments