InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Heap & Priority Queue

Total Cost to Hire K Workers

medium Original ↗ 00:00

Problem

You have a row of workers; costs[i] is the price of hiring the i-th worker. You must run exactly k hiring sessions, hiring exactly one worker per session, under these rules:

  • In each session you may only consider the first candidates workers and the last candidates workers still in the row (the two groups may overlap if few workers remain).
  • Among those considered, hire the one with the lowest cost; break ties by the smaller original index (i.e. the front group wins ties).
  • A hired worker leaves the row and is never considered again.

Return the total cost of the k hires.

Examples

  • costs = [17,12,10,2,7,2,11,20,8], k = 3, candidates = 411 Session 1 considers [17,12,10,2] and [2,11,20,8]; both 2s tie, the front one (index 3) is hired. Session 2 hires the other 2 (now in the back group). Session 3’s cheapest visible worker is 7. Total 2 + 2 + 7 = 11.
  • costs = [1,2,4,1], k = 3, candidates = 34 The windows cover the whole row, so we just take the three cheapest: 1 + 1 + 2 = 4.
  • costs = [5,3,3], k = 2, candidates = 16 Session 1 sees {5, 3} (front index 0, back index 2) and hires the back 3. Session 2 sees {5, 3} again and hires the remaining 3. Total 6.

Constraints

  • 1 <= costs.length <= 10^5
  • 1 <= costs[i] <= 10^5
  • 1 <= k, candidates <= costs.length

Think about it first

Hint 1 Each session only ever looks at a window on the left end and a window on the right end. What happens to those windows when a worker is hired from one of them?
Hint 2 Hiring from the front window pulls in the next unseen worker from the left; hiring from the back pulls from the right. You repeatedly need "the minimum of a set that gains and loses one element" — that is exactly a min-heap.
Hint 3 Keep two min-heaps (front and back) plus two pointers `i`, `j` marking the unseen middle. Each session: refill both heaps to `candidates` elements while `i <= j`, then pop from the cheaper heap, preferring the front heap on ties.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug