Problem Description
Given an array of worker hiring costs, you must conduct k hiring sessions. In each session you choose one worker from one of two candidate pools: the first "candidates" workers or the last "candidates" workers. The worker with the lowest cost is chosen; if costs are equal, the one with the lower index is chosen. When a worker is hired, the candidate pool from which the worker came is replenished from the remaining workers (if any). The goal is to determine the total cost to hire exactly k workers.
Key Insights
- Use two candidate pools (left and right) representing the first and last portions of the array.
- A min-heap (priority queue) efficiently retrieves the worker with the lowest cost; store (cost, index) to automatically break ties by index.
- Maintain two pointers to track the next potential candidate in the middle after each hire.
- Take care of overlapping when the candidate pools intersect.
Space and Time Complexity
Time Complexity: O(k log(candidates))
Space Complexity: O(candidates)
Solution
We use two min-heaps: one for the left candidate pool and one for the right candidate pool. Initialize the left heap with the first "candidates" workers and the right heap with the last "candidates" workers (ensuring no overlap). For each hiring session (total k sessions), compare the top elements (lowest cost and then the smallest index) from both heaps. Once a worker is hired from a heap, if there are remaining workers outside the current candidate pool, add the next available worker from that side into the heap. This simulation approach with heaps efficiently retrieves the smallest cost candidate in each session.