Skip to content
Decoder

Total Cost to Hire K Workers

Medium

Problem

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.

Example 1

Input
costs = [17, 12, 10, 2, 7, 2, 11, 20, 8], k = 3, candidates = 4
Output
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

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.