InterviewPrepKit

Home / Coding / Heap & Priority Queue

Total Cost to Hire K Workers

medium Original β†—
Solving tips
  • Recognize 'repeatedly extract the min from a set that changes by one element' at each end of the array: model the two windows as two min-heaps fed by pointers i (left) and j (right).
  • Each session, refill both heaps to 'candidates' size while i <= j, then pop from the cheaper heap; break ties toward the front heap using a strict '<' on the back heap.
  • The i <= j guard is what prevents the same worker entering both heaps when the windows overlap; guard pops with empty-heap checks near the end.
  • Target O((k + candidates) log candidates) time, O(candidates) space; when 2*candidates >= n the windows cover everything and the answer is just the k cheapest via a sort.

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 = 4 β†’ 11 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 = 3 β†’ 4 The windows cover the whole row, so we just take the three cheapest: 1 + 1 + 2 = 4.
  • costs = [5,3,3], k = 2, candidates = 1 β†’ 6 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.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.