AAlgoLoopSpaced repetition for LeetCode
MEDIUMHeap / Priority QueueLeetCode ↗

Total Cost to Hire K Workers

The key idea

Only the two ends of the array can ever hold a current candidate. Keep one min-heap for the first candidates workers and another for the last candidates, and each round hire the cheaper top (ties go to the front), then refill from the shrinking middle.

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. You 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, breaking the tie by the smallest index.
- A worker can only be chosen once.

Return the total cost to hire exactly k workers.

Constraints

Examples

Input: costs = [17,12,10,2,7,2,11,20,8], k = 3, candidates = 4 Output: 11
Input: costs = [1,2,4,1], k = 3, candidates = 3 Output: 4

Complexity

Time: O((k + candidates) log candidates) Space: O(candidates)

See the full solution

410310
Step-by-step visualization
Start free →

More Heap / Priority Queue problems