Minimum Cost to Hire K Workers
Description
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 1:
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.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3 Output: 30.66667 Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000
, whereN = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
- Answers within
10^-5
of the correct answer will be considered correct.
Solution(javascript)
const MaxHeap = () => {
const list = []
const parent = index => Math.floor((index - 1) / 2)
const left = index => 2 * index + 1
const right = index => 2 * index + 2
const swap = (a, b) => {
const temp = list[a]
list[a] = list[b]
list[b] = temp
}
const insert = (x) => {
list.push(x)
let currentIndex = list.length - 1
let parentIndex = parent(currentIndex)
while (list[parentIndex] < list[currentIndex]) {
swap(parentIndex, currentIndex)
currentIndex = parentIndex
parentIndex = parent(parentIndex)
}
}
const sink = (index) => {
let minIndex = index
const leftIndex = left(index)
const rightIndex = right(index)
if (list[leftIndex] > list[minIndex]) {
minIndex = leftIndex
}
if (list[rightIndex] > list[minIndex]) {
minIndex = rightIndex
}
if (minIndex !== index) {
swap(minIndex, index)
sink(minIndex)
}
}
const size = () => list.length
const extract = () => {
swap(0, size() - 1)
const min = list.pop()
sink(0)
return min
}
return {
insert,
size,
extract,
}
}
/**
* @param {number[]} quality
* @param {number[]} wage
* @param {number} K
* @return {number}
*/
const mincostToHireWorkers = function (quality, wage, K) {
const works = quality.map((q, index) => [q, wage[index]])
works.sort((a, b) => (a[1] / a[0]) - (b[1] / b[0]))
let totalQuantity = 0
const maxHeap = MaxHeap()
let min = Infinity
for (const work of works) {
maxHeap.insert(work[0])
totalQuantity += work[0]
if (maxHeap.size() > K) {
const max = maxHeap.extract()
totalQuantity -= max
}
if (maxHeap.size() === K) {
min = Math.min(
min,
totalQuantity * (work[1] / work[0]),
)
}
}
return min
}