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
assert Solution().totalCost([17, 12, 10, 2, 7, 2, 11, 20, 8], 3, 4) == 11
assert Solution().totalCost([1, 2, 4, 1], 3, 3) == 4
assert Solution().totalCost([5], 1, 1) == 5
assert Solution().totalCost([2, 2, 2, 2], 2, 1) == 4
class Solution {
public long totalCost(int[] costs, int k, int candidates) {
PriorityQueue<Integer> front = new PriorityQueue<>(), back = new PriorityQueue<>();
int i = 0, j = costs.length - 1;
long total = 0;
while (k-- > 0) {
while (front.size() < candidates && i <= j) front.add(costs[i++]);
while (back.size() < candidates && i <= j) back.add(costs[j--]);
if (back.isEmpty() || (!front.isEmpty() && front.peek() <= back.peek())) total += front.poll();
else total += back.poll();
}
return total;
}
}
type IntHeap []int // min-heap
func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x any) { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
func totalCost(costs []int, k int, candidates int) int64 {
i, j := 0, len(costs)-1
front, back := &IntHeap{}, &IntHeap{}
total := 0
for ; k > 0; k-- {
for front.Len() < candidates && i <= j {
heap.Push(front, costs[i])
i++
}
for back.Len() < candidates && i <= j {
heap.Push(back, costs[j])
j--
}
if back.Len() == 0 || (front.Len() > 0 && (*front)[0] <= (*back)[0]) { // ties go to the front
total += heap.Pop(front).(int)
} else {
total += heap.Pop(back).(int)
}
}
return int64(total)
}