Total Cost to Hire K Workers
Problem Statement
You have n workers. Worker i asks for costs[i] coins. You must hire exactly k workers, one per session.
In each session, look at the first candidates workers who are still unhired, and the last candidates workers who are still unhired. Hire the cheapest worker from those two groups. If two of them cost the same, hire the one with the smaller original index. A hired worker cannot be hired again.
If the two groups overlap (fewer than 2 × candidates workers remain), every remaining worker is a candidate.
Return the total cost of the k workers you hire.
costs, an integer array, and two integers k and candidates.
The total cost of the k hired workers, as a 64-bit number.
Session 1: the first four are [17,12,10,2] and the last four are [2,11,20,8]. Both cost-2 workers qualify, and the one at index 3 has the smaller index, so hire it. Session 2: the other cost-2 worker (index 5) is now among the last four, so hire it. Session 3: the cheapest candidate is the cost-7 worker at index 4. 2 + 2 + 7 = 11.
Only 4 workers remain and 2 × 3 > 4, so every worker is a candidate. Hire the cost-1 worker at index 0, then the cost-1 worker at index 3, then the cost-2 worker at index 1. 1 + 1 + 2 = 4.
- • 1 ≤ costs.length ≤ 10^5
- • 1 ≤ costs[i] ≤ 10^5
- • 1 ≤ k, candidates ≤ costs.length
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Each session, check the first and last candidates; hire the cheapest and remove it from the list
A min-heap for the left end and one for the right end, fed by two pointers that never overlap
Keep the unhired workers in a plain list, in their original order. Each session, look only at the two ends, the first and last candidates workers, take the cheapest (ties go to the smaller index), remove it from the list, and repeat for k sessions.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Two Heaps translate into production architectures and low-level memory mechanics.