# Program to find minimum cost to hire k workers in Python

Suppose we have an array called quality for each different worker, and have another array called wages and a value K. The i-th worker has a quality[i] and a minimum wage expectation wage[i]. We want to hire K workers to form a paid group. When we are hiring a group of K workers, we must pay them according to the following rules:

• Each worker in the paid group should be paid in the ratio of their quality by comparing with others in the paid group.

• Every worker in the paid group must be paid at least their minimum wage expectation.

We have to find the least amount of money needed to form a paid group satisfying the above conditions.

So, if the input is like quality = [10,22,5], wage = [70,52,30] and K = 2, then the output will be 105.000 because we will pay 70 to the first worker and 35 to the 3rd worker.

To solve this, we will follow these steps −

• qr := a new list

• for each pair (q, w) from quality and wage, do

• insert (w/q, q) at the end of qr

• sort the list qr

• cand := a new list, csum := 0

• for i in range 0 to K - 1, do

• insert -qr[i, 1] into heap cand

• csum := csum + qr[i, 1]

• ans := csum * qr[K - 1, 0]

• for idx in range K to size of quality, do

• insert -qr[i, 1] into heap cand

• csum := csum + qr[idx, 1] + top element from heap cand and delete it from heap

• ans = minimum of ans and (csum * qr[idx])

• return ans

## Example

Let us see the following implementation to get better understanding

import heapq
def solve(quality, wage, K):
qr = []
for q, w in zip(quality, wage):
qr.append([w/q, q])
qr.sort()

cand, csum = [], 0
for i in range(K):
heapq.heappush(cand, -qr[i])
csum += qr[i]
ans = csum * qr[K - 1]

for idx in range(K, len(quality)):
heapq.heappush(cand, -qr[idx])
csum += qr[idx] + heapq.heappop(cand)
ans = min(ans, csum * qr[idx])
return ans

quality = [10,22,5]
wage = [70,52,30]
K = 2
print(solve(quality, wage, K))

## Input

[10,22,5], [70,52,30], 2


## Output

105