SDE & MLE Prep

2462. Total Cost to Hire K Workers

Problem

Hire k workers in k rounds. Each round, pick the cheapest worker among the first candidates and the last candidates workers still available (ties go to the smaller index); hired workers leave the line. Return the total cost.

Example: costs = [17,12,10,2,7,2,11,20,8], k = 3, candidates = 4 → 11 (2 + 2 + 7)

Constraints: n ≤ 10⁵.

Two min-heaps: the first candidates workers and the last candidates workers (never overlapping — the pointers i ≤ j guarantee each worker is in at most one heap). Each round hire the cheaper top (front wins ties: smaller index), then refill that side from the middle.

Complexity: O((k + candidates) log candidates).

class Solution:
    def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
        i, j = 0, len(costs) - 1
        front, back, total = [], [], 0
        for _ in range(k):
            while len(front) < candidates and i <= j:
                heappush(front, costs[i])
                i += 1
            while len(back) < candidates and i <= j:
                heappush(back, costs[j])
                j -= 1
            if not back or (front and front[0] <= back[0]):
                total += heappop(front)
            else:
                total += heappop(back)
        return total