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?- A. 54.00
- B. 60.00
- C. 58.00
- 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
- Problem: In a sorted array every value appears twice except one. Find it in O(log n) using index parity. python def single(a): lo, hi = 0…
- Problem: Split an array into contiguous parts of length at most k; every element of a part becomes that part's maximum. Maximise the final…
- Problem: Build a binary tree whose leaves (in order) are the array values; each internal node's value is (max leaf on its left) × (max…
- Problem: Longest arithmetic subsequence (not necessarily contiguous) using a dictionary of (difference → length) per index. python def…
- Problem: Count all square submatrices made entirely of 1s. python def count(m): R, C = len(m), len(m[0]); tot = 0 dp = [row[:] for row in…
- Problem: Paint n fence posts with k colours so that no three consecutive posts share a colour. python def ways(n, k): same, diff = 0, k…