Total Cost to Hire K Workers (LeetCode 2462): Solution and Explanation
Run k hiring sessions. Each session hires the cheapest worker among the first candidates and the last candidates still available, breaking ties by the smaller index. Return the total cost, which can exceed 32 bits.
Intuition
Only the two ends of the line are ever visible. Whatever sits in the middle cannot be hired until a window shrinks and pulls it in.
So keep each window in its own min-heap. The cheapest visible worker is always one of the two heap tops.
Hiring removes one worker from one window. Only that window needs a refill, and it takes the next worker from its side of the middle, tracked by pointers i and j.
Every index in the left heap is smaller than every index in the right heap, so a tie between the tops always goes to the left.
Approach: Two min-heaps with middle pointers
- Set i = 0 and j = n - 1. They mark the workers no window has reached yet.
- Before each session, push costs[i++] into the left heap until it holds
candidatesworkers or i passes j. Do the same for the right heap with costs[j--]. - Hire the left top if the right heap is empty or the left top is no larger. Otherwise hire the right top. Add the cost to a 64-bit total.
- After k sessions return the total. Once i > j the heaps already hold every remaining worker and nothing is refilled.
Step-by-step example
costs = [17,12,10,2,7,2,11,20,8], k = 3, candidates = 4
- Left heap gets 17, 12, 10, 2 (indices 0-3). Right heap gets 8, 20, 11, 2 (indices 8-5). Only index 4 (cost 7) is in the middle.
- Session 1: both tops cost 2. The tie goes left, so hire index 3. Total 2.
- Session 2: the left heap refills with 7 from the middle, and now i > j. Left top 7, right top 2, so hire index 5. Total 4.
- Session 3: no refill is possible. Left top 7 beats right top 8. Total 11.
Code: Python, Java, C++
1class Solution:
2 def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
3 left, right = [], []
4 i, j = 0, len(costs) - 1
5 total = 0
6 for _ in range(k):
7 while len(left) < candidates and i <= j:
8 heapq.heappush(left, costs[i])
9 i += 1
10 while len(right) < candidates and i <= j:
11 heapq.heappush(right, costs[j])
12 j -= 1
13 if left and (not right or left[0] <= right[0]):
14 total += heapq.heappop(left)
15 else:
16 total += heapq.heappop(right)
17 return total1class Solution {
2 public long totalCost(int[] costs, int k, int candidates) {
3 PriorityQueue<Integer> left = new PriorityQueue<>();
4 PriorityQueue<Integer> right = new PriorityQueue<>();
5 int i = 0, j = costs.length - 1;
6 long total = 0;
7 for (int s = 0; s < k; s++) {
8 while (left.size() < candidates && i <= j) {
9 left.offer(costs[i++]);
10 }
11 while (right.size() < candidates && i <= j) {
12 right.offer(costs[j--]);
13 }
14 if (!left.isEmpty() && (right.isEmpty() || left.peek() <= right.peek())) {
15 total += left.poll();
16 } else {
17 total += right.poll();
18 }
19 }
20 return total;
21 }
22}1class Solution {
2public:
3 long long totalCost(vector<int>& costs, int k, int candidates) {
4 priority_queue<int, vector<int>, greater<int>> left, right;
5 int i = 0, j = (int)costs.size() - 1;
6 long long total = 0;
7 for (int s = 0; s < k; s++) {
8 while ((int)left.size() < candidates && i <= j) {
9 left.push(costs[i++]);
10 }
11 while ((int)right.size() < candidates && i <= j) {
12 right.push(costs[j--]);
13 }
14 if (!left.empty() && (right.empty() || left.top() <= right.top())) {
15 total += left.top();
16 left.pop();
17 } else {
18 total += right.top();
19 right.pop();
20 }
21 }
22 return total;
23 }
24};Time and space complexity
O((k + candidates) log candidates)
Each heap holds at most candidates workers. There are at most 2 * candidates + k pushes and k pops, each logarithmic.
O(candidates)
The two heaps hold at most 2 * candidates workers.
Other approaches
Single heap tagged by side (time O((k + candidates) log candidates), space O(candidates))
Push (cost, index) pairs into one min-heap and remember which side each came from, so you know which pointer refills after a pop. Same complexity, and the index breaks ties directly.
Scan both windows each session (time O(k * (n + candidates)), space O(n))
Rebuild the visible set from a list of remaining workers every session and take its minimum. Easy to get right, but too slow for 10^5 workers.
Common mistakes
- Letting the two windows overlap when 2 * candidates exceeds n, so one worker sits in both heaps and is hired twice. The i <= j check prevents it.
- Refilling a window after the pointers have crossed.
- Breaking a tie toward the right heap. The left heap always holds the smaller indices.
- Summing in a 32-bit int. Up to 10^5 hires of large costs overflow it.
Frequently asked questions
Why do the heaps not need indices to break ties?
Within one heap, equal costs add the same amount to the total whichever one is hired first. Between heaps, every left index is smaller than every right index, so preferring the left top on a tie gives exactly the smallest index.
What happens when the windows meet?
Once i passes j, every remaining worker is already in one of the heaps. Refills stop and the sessions simply keep taking the cheaper top, which is the cheapest remaining worker.
Why does the answer need 64 bits?
The total is a sum of up to k costs. Large costs over many sessions pass 2^31 - 1 easily, so use long, long long or int64.