Skip to content

Total Cost to Hire K Workers

MediumHeap / Priority Queue
Decode it first. Clues, constraints, pattern and plan before any code.

Workers stand in a line, and costs[i] is the cost of hiring worker i. You will run k hiring rounds, hiring exactly one worker per round:

  • Look only at the first candidates workers and the last candidates workers still in line (fewer if the line is short; a worker is never counted twice).
  • Hire the cheapest of them. On a tie, hire the one with the smaller index.
  • That worker leaves the line.

Return the total cost of the k hires.

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

Round 1 looks at [17, 12, 10, 2] and [2, 11, 20, 8] and hires the 2 at index 3. Round 2 hires the other 2. Round 3 hires the 7. Total 2 + 2 + 7 = 11.

Constraints

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