Browse curriculum

Total Cost to Hire K Workers (LeetCode 2462)

Total Cost to Hire K Workers (LeetCode 2462): hire k workers, each round taking the cheapest among the first and last candidates workers. Keep two min-heaps, one per end, hire the cheaper top and refill from the untouched middle.

Problem Understanding

Total Cost to Hire K Workers (LeetCode 2462): costs[i] is the cost of hiring worker i. Run k hiring sessions; in each one, choose the cheapest worker among the first candidates workers and the last candidates workers still available, breaking ties by the smaller index, and remove them. Return the total cost.

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

The Intuition: A Heap at Each End of the Line

Each round only looks at the two ends of the line, and the cheapest at each end is what matters. A min-heap per end gives that in O(log c).

  1. Two heaps and two pointers. left holds the first candidates, right the last candidates; the middle i..j has not been looked at yet.
  2. Top up each heap from its end of the middle while it has fewer than candidates and i <= j.
  3. Hire the cheaper top. On a tie take the left one: its index is smaller.
  4. Repeat k times.

This is the heap pattern from Kth Largest Element in an Array combined with the two pointers that shrink a range from both ends, as in Container With Most Water.

Total Cost to Hire K Workers Visualization

k = 3 · candidates = 4 · OUTLINED = LEFT HEAP · TINTED = RIGHT HEAP

TOP UP BOTH HEAPS

17

0

12

1

10

2

2

3

i j

7

4

2

5

11

6

20

7

8

8

round

1

total

0

left heap (top first)

2 (#3)
10 (#2)
12 (#1)
17 (#0)

right heap (top first)

2 (#5)
8 (#8)
11 (#6)
20 (#7)

 

Round 1: top the heaps up from the middle to 4 workers each where possible (8 added)

Next

Round 1: hire worker 3 (cost 2) from the left heap, 2 <= 2. Total 2

Free preview: the first 3 of 6 steps

costs

k

3

candidates

4

The row is the line of workers. The left heap’s workers are outlined, the right heap’s are tinted, and i and j mark the untouched middle. Hired workers turn green. The aside lists each heap with its top first. Try Tie and Cheap middle, where the cheapest workers start out of reach.

Total Cost to Hire K Workers Dry Run

Input: costs = [17,12,10,2,7,2,11,20,8], k = 3, candidates = 4.

Round Left heap Right heap Hire Total
1 17, 12, 10, 2 2, 11, 20, 8 worker 3 (2), tie goes left 2
2 refill 7: 17, 12, 10, 7 2, 11, 20, 8 worker 5 (2) 4
3 17, 12, 10, 7 11, 20, 8 (middle used up) worker 4 (7) 11

Answer: 11.

Total Cost to Hire K Workers LeetCode Solution

Two min-heaps, two pointers and k rounds. JavaScript and TypeScript bring a small MinHeap; C keeps two array heaps. The total can pass 2³¹, so Java, C++ and C use 64-bit integers.

Total Cost to Hire K Workers Code
1class MinHeap {
2 constructor(less = (a, b) => a < b) {
3 this.items = [];
4 this.less = less;
5 }
6
7 size() {
8 return this.items.length;
9 }
10
11 peek() {
12 return this.items[0];
13 }
14
15 push(x) {
16 const a = this.items;
17 a.push(x);
18 let i = a.length - 1;
19 while (i > 0 && this.less(a[i], a[(i - 1) >> 1])) {
20 const p = (i - 1) >> 1;
21 [a[i], a[p]] = [a[p], a[i]];
22 i = p;
23 }
24 }
25
26 pop() {
27 const a = this.items;
28 const top = a[0];
29 const last = a.pop();
30 if (a.length > 0) {
31 a[0] = last;
32 let i = 0;
33 while (true) {
34 const l = 2 * i + 1, r = l + 1;
35 let m = i;
36 if (l < a.length && this.less(a[l], a[m])) m = l;
37 if (r < a.length && this.less(a[r], a[m])) m = r;
38 if (m === i) break;
39 [a[i], a[m]] = [a[m], a[i]];
40 i = m;
41 }
42 }
43 return top;
44 }
45}
46
47var totalCost = function(costs, k, candidates) {
48 const left = new MinHeap(), right = new MinHeap();
49 let i = 0, j = costs.length - 1, total = 0;
50 for (let round = 0; round < k; round++) {
51 while (left.size() < candidates && i <= j) {
52 left.push(costs[i++]);
53 }
54 while (right.size() < candidates && i <= j) {
55 right.push(costs[j--]);
56 }
57 if (right.size() === 0 || (left.size() > 0 && left.peek() <= right.peek())) {
58 total += left.pop();
59 } else {
60 total += right.pop();
61 }
62 }
63 return total;
64};

Total Cost to Hire K Workers in Python, Java, C++, TypeScript and C

Total Cost to Hire K Workers in Python
class Solution:
    def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
        left, right = [], []
        i, j = 0, len(costs) - 1
        total = 0
        for _ in range(k):
            while len(left) < candidates and i <= j:
                heapq.heappush(left, costs[i])
                i += 1
            while len(right) < candidates and i <= j:
                heapq.heappush(right, costs[j])
                j -= 1
            if not right or (left and left[0] <= right[0]):
                total += heapq.heappop(left)
            else:
                total += heapq.heappop(right)
        return total
Total Cost to Hire K Workers in Java
class Solution {
    public long totalCost(int[] costs, int k, int candidates) {
        PriorityQueue<Integer> left = new PriorityQueue<>(), right = new PriorityQueue<>();
        int i = 0, j = costs.length - 1;
        long total = 0;
        for (int round = 0; round < k; round++) {
            while (left.size() < candidates && i <= j) {
                left.offer(costs[i++]);
            }
            while (right.size() < candidates && i <= j) {
                right.offer(costs[j--]);
            }
            if (right.isEmpty() || (!left.isEmpty() && left.peek() <= right.peek())) {
                total += left.poll();
            } else {
                total += right.poll();
            }
        }
        return total;
    }
}
Total Cost to Hire K Workers in C++
class Solution {
public:
    long long totalCost(vector<int>& costs, int k, int candidates) {
        priority_queue<int, vector<int>, greater<int>> left, right;
        int i = 0, j = costs.size() - 1;
        long long total = 0;
        for (int round = 0; round < k; round++) {
            while ((int)left.size() < candidates && i <= j) {
                left.push(costs[i++]);
            }
            while ((int)right.size() < candidates && i <= j) {
                right.push(costs[j--]);
            }
            if (right.empty() || (!left.empty() && left.top() <= right.top())) {
                total += left.top();
                left.pop();
            } else {
                total += right.top();
                right.pop();
            }
        }
        return total;
    }
};
Total Cost to Hire K Workers in TypeScript
class MinHeap<T> {
    private items: T[] = [];

    constructor(private less: (a: T, b: T) => boolean = (a, b) => a < b) {}

    size(): number {
        return this.items.length;
    }

    peek(): T {
        return this.items[0];
    }

    push(x: T): void {
        const a = this.items;
        a.push(x);
        let i = a.length - 1;
        while (i > 0 && this.less(a[i], a[(i - 1) >> 1])) {
            const p = (i - 1) >> 1;
            [a[i], a[p]] = [a[p], a[i]];
            i = p;
        }
    }

    pop(): T {
        const a = this.items;
        const top = a[0];
        const last = a.pop()!;
        if (a.length > 0) {
            a[0] = last;
            let i = 0;
            while (true) {
                const l = 2 * i + 1, r = l + 1;
                let m = i;
                if (l < a.length && this.less(a[l], a[m])) m = l;
                if (r < a.length && this.less(a[r], a[m])) m = r;
                if (m === i) break;
                [a[i], a[m]] = [a[m], a[i]];
                i = m;
            }
        }
        return top;
    }
}

function totalCost(costs: number[], k: number, candidates: number): number {
    const left = new MinHeap<number>(), right = new MinHeap<number>();
    let i = 0, j = costs.length - 1, total = 0;
    for (let round = 0; round < k; round++) {
        while (left.size() < candidates && i <= j) {
            left.push(costs[i++]);
        }
        while (right.size() < candidates && i <= j) {
            right.push(costs[j--]);
        }
        if (right.size() === 0 || (left.size() > 0 && left.peek() <= right.peek())) {
            total += left.pop();
        } else {
            total += right.pop();
        }
    }
    return total;
}
Total Cost to Hire K Workers in C
static void push(int* h, int* size, int v) {
    int i = (*size)++;
    h[i] = v;
    while (i > 0 && h[(i - 1) / 2] > h[i]) {
        int p = (i - 1) / 2, t = h[p];
        h[p] = h[i];
        h[i] = t;
        i = p;
    }
}

static int pop(int* h, int* size) {
    int top = h[0], i = 0;
    h[0] = h[--(*size)];
    for (;;) {
        int m = i, l = 2 * i + 1, r = l + 1;
        if (l < *size && h[l] < h[m]) m = l;
        if (r < *size && h[r] < h[m]) m = r;
        if (m == i) return top;
        int t = h[m];
        h[m] = h[i];
        h[i] = t;
        i = m;
    }
}

long long totalCost(int* costs, int costsSize, int k, int candidates) {
    int* left = malloc((candidates + 1) * sizeof(int));
    int* right = malloc((candidates + 1) * sizeof(int));
    int ls = 0, rs = 0, i = 0, j = costsSize - 1;
    long long total = 0;
    for (int round = 0; round < k; round++) {
        while (ls < candidates && i <= j) {
            push(left, &ls, costs[i++]);
        }
        while (rs < candidates && i <= j) {
            push(right, &rs, costs[j--]);
        }
        if (rs == 0 || (ls > 0 && left[0] <= right[0])) {
            total += pop(left, &ls);
        } else {
            total += pop(right, &rs);
        }
    }
    free(left);
    free(right);
    return total;
}

Edge Cases & Common Mistakes

  • Taking a worker twice: refill only while i <= j, so the two heaps never share a worker.
  • Breaking ties to the right: the smaller index wins, which is always the left heap; compare with <=.
  • An empty heap: when one side runs dry, hire from the other.
  • 2 × candidates covering the whole array: the heaps hold everyone, and the answer is the sum of the k cheapest costs.

Summary

Two min-heaps over the first and last candidates, two pointers over the untouched middle. Each round, top both heaps up, hire the cheaper top (left on a tie) and add its cost. O((k + c) log c) time, O(c) space.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Fill the heaps

    Push the first candidates costs into the left heap and the last candidates into the right heap, moving i right and j left, never past each other.

  2. Hire

    Pop the cheaper top (the left one on a tie) and add its cost.

  3. Refill and repeat

    Top both heaps up from the middle and repeat for k rounds.

Frequently asked questions

Why two heaps instead of one?

Each round may only look at the first `candidates` and the last `candidates` remaining workers. Two heaps keep those two groups apart, and two pointers i and j mark the untouched middle, so refilling after a hire takes one worker from the correct end. One heap would need to know which end each worker came from to refill correctly.


How are ties broken?

The problem picks the lower index on a tie. Every worker in the left heap has a smaller index than every worker in the right heap, so comparing with `<=` sends ties to the left. Inside one heap, equal costs give the same total whichever is taken first.


What happens when the two groups overlap?

When fewer than 2 × candidates workers remain, the pointers meet and refilling stops: i > j. From then on the two heaps together hold every remaining worker, and the rounds just take the cheapest of them, which is what the rules say should happen.


What is the complexity?

Each worker enters a heap at most once and each round pops once, so there are at most k + 2c pushes and k pops on heaps of size at most c: O((k + c) log c) time and O(c) extra space.

New to the technique behind this problem? Watch it run step by step:

Heaps Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description