Total Cost to Hire K Workers - Problem

You are given a 0-indexed integer array costs where costs[i] is the cost of hiring the i-th worker.

You are also given two integers k and candidates. We want to hire exactly k workers according to the following rules:

  • You will run k sessions and hire exactly one worker in each session.
  • In each hiring session, choose the worker with the lowest cost from either the first candidates workers or the last candidates workers. Break the tie by the smallest index.
  • If there are fewer than candidates workers remaining, choose the worker with the lowest cost among them. Break the tie by the smallest index.
  • A worker can only be chosen once.

Return the total cost to hire exactly k workers.

Input & Output

Example 1 — Basic Case
$ Input: costs = [17,12,10,2,7,2,11,20,8], k = 3, candidates = 4
Output: 11
💡 Note: Session 1: First 4 = [17,12,10,2], Last 4 = [2,11,20,8]. Pick min = 2 (index 3). Session 2: First 4 = [17,12,10,7], Last 4 = [2,11,20,8]. Pick min = 2 (index 5). Session 3: First 4 = [17,12,10,7], Last 3 = [11,20,8]. Pick min = 7. Total = 2+2+7 = 11
Example 2 — Small Array
$ Input: costs = [1,2,4,1], k = 3, candidates = 3
Output: 4
💡 Note: Since candidates=3 covers most of array, we pick 3 cheapest: 1, 1, 2. Total = 1+1+2 = 4
Example 3 — Equal Costs
$ Input: costs = [2,2,2,2,2], k = 2, candidates = 2
Output: 4
💡 Note: All costs are equal, so we pick by smallest index. Choose indices 0 and 1, both cost 2. Total = 2+2 = 4

Constraints

  • 1 ≤ k, candidates ≤ costs.length ≤ 105
  • 1 ≤ costs[i] ≤ 105

Visualization

Tap to expand
Hire K Workers: Choose cheapest from candidate poolscosts=[17,12,10,2,7,2,11,20,8], k=3, candidates=417121027211208012345678First 4 CandidatesLast 4 CandidatesHiring Process:Session 1: Min from candidates = 2 (index 3) ✓Session 2: Min from candidates = 2 (index 5) ✓Session 3: Min from candidates = 7 (index 4) ✓Total Cost: 2 + 2 + 7 = 11
Understanding the Visualization
1
Input
Array of worker costs with k hiring sessions
2
Process
Pick cheapest from first/last candidates each session
3
Output
Sum of costs for k hired workers
Key Takeaway
🎯 Key Insight: Use two heaps to efficiently find the cheapest worker from candidate pools at both ends
Asked in
Amazon 15 Google 12 Microsoft 8
23.5K Views
Medium Frequency
~25 min Avg. Time
834 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen