Problem
You are given a 0-indexed integer array costs
where costs[i]
is the cost of hiring the ith
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 lastcandidates
workers. Break the tie by the smallest index. - For example, if
costs = [3,2,7,7,1,2]
andcandidates = 2
, then in the first hiring session, we will choose the4th
worker because they have the lowest cost[_3,2_ ,7,7,_**1** ,2_]
. - In the second hiring session, we will choose
1st
worker because they have the same lowest cost as4th
worker but they have the smallest index[_3,**2**_ ,7,_7,2_]
. Please note that the indexing may be changed in the process. - 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 exactlyk
workers.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= costs.length <= 10^5
1 <= costs[i] <= 10^5
1 <= k, candidates <= costs.length
Solution
Method 1 – Two Heaps (Priority Queues)
Intuition
Use two min-heaps to always pick the lowest cost from the first and last candidates
workers, simulating the hiring process efficiently.
Approach
Maintain two pointers and two heaps for the left and right candidate windows. At each step, pop the smallest from either heap, and refill the heap from the next available index. Repeat for k hires.
Code
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(k log candidates)
- 🧺 Space complexity:
O(candidates)