Skip to content

Commit 040c6e7

Browse files
committed
Add solution #857
1 parent cb5cf7f commit 040c6e7

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -664,6 +664,7 @@
664664
854|[K-Similar Strings](./0854-k-similar-strings.js)|Hard|
665665
855|[Exam Room](./0855-exam-room.js)|Medium|
666666
856|[Score of Parentheses](./0856-score-of-parentheses.js)|Medium|
667+
857|[Minimum Cost to Hire K Workers](./0857-minimum-cost-to-hire-k-workers.js)|Hard|
667668
867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy|
668669
868|[Binary Gap](./0868-binary-gap.js)|Easy|
669670
872|[Leaf-Similar Trees](./0872-leaf-similar-trees.js)|Easy|
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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

Comments
 (0)