Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Hire exactly K workers; each is paid in proportion to quality, and at least their minimum wage. Minimise total pay (sort by wage/quality ratio, keep the K smallest qualities in a max-heap).

Problem: Hire exactly K workers; each is paid in proportion to quality, and at least their minimum wage. Minimise total pay (sort by wage/quality ratio, keep the K smallest qualities in a max-heap).
import heapq
def hire(q, w, K):
    ws = sorted((w[i] / q[i], q[i]) for i in range(len(q)))
    h, qs, best = [], 0, float('inf')
    for r, qi in ws:
        heapq.heappush(h, -qi); qs += qi
        if len(h) > K: qs += heapq.heappop(h)
        if len(h) == K: best = min(best, r * qs)
    return f"{best:.2f}"
print(hire([4, 8, 2, 6, 3], [20, 24, 12, 30, 9], 3))
What is printed?
  1. A. 54.00
  2. B. 60.00
  3. C. 58.00
  4. D. 72.00

Correct answer: A. 54.00

With the group's highest ratio r as the captain, everyone is paid r × quality, so the cost is r × Σq. Scanning ratios in increasing order and keeping the K smallest qualities seen so far finds the minimum, 54.00, matching all C(5, 3) groups checked by brute force.

More Coding Interview Problems questions

Exams that ask this topic