VISUALGO//PROBLEMS
total cost to hire k workers · heap / priority queuemedium
left heap
right heap
round
·
total
·
costs
·
·
·
·
·
·
·
·
·
ELEMENTS
costs
k
candidates
Python
import heapq
def totalCost(costs: list[int], k: int, candidates: int) -> int:
left, right = [], []
lo, hi = 0, len(costs) - 1
total = 0
for _ in range(k):
while len(left) < candidates and lo <= hi:
heapq.heappush(left, costs[lo])
lo += 1
while len(right) < candidates and lo <= hi:
heapq.heappush(right, costs[hi])
hi -= 1
if not right or (left and left[0] <= right[0]):
total += heapq.heappop(left)
else:
total += heapq.heappop(right)
return total