2462. Total Cost to Hire K Workers
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:
k
sessions and hire exactly one worker in each session.candidates
workers or the last candidates
workers. Break the tie by the smallest index.
costs = [3,2,7,7,1,2]
and candidates = 2
, then in the first hiring session, we will choose the 4th worker because they have the lowest cost [3,2,7,7,1,2]
.[3,2,7,7,2]
. Please note that the indexing may be changed in the process.Return the total cost to hire exactly k
workers.
Example 1:
Input: costs = [17,12,10,2,7,2,11,20,8], k = 3, candidates = 4
Output: 11
Explanation: We hire 3 workers in total. The total cost is initially 0.
- In the first hiring round we choose the worker from [17,12,10,2,7,2,11,20,8]. The lowest cost is 2, and we break the tie by the smallest index, which is 3. The total cost = 0 + 2 = 2.
- In the second hiring round we choose the worker from [17,12,10,7,2,11,20,8]. The lowest cost is 2 (index 4). The total cost = 2 + 2 = 4.
- In the third hiring round we choose the worker from [17,12,10,7,11,20,8]. The lowest cost is 7 (index 3). The total cost = 4 + 7 = 11. Notice that the worker with index 3 was common in the first and last four workers.
The total hiring cost is 11.
Example 2:
Input: costs = [1,2,4,1], k = 3, candidates = 3
Output: 4
Explanation: We hire 3 workers in total. The total cost is initially 0.
- In the first hiring round we choose the worker from [1,2,4,1]. The lowest cost is 1, and we break the tie by the smallest index, which is 0. The total cost = 0 + 1 = 1. Notice that workers with index 1 and 2 are common in the first and last 3 workers.
- In the second hiring round we choose the worker from [2,4,1]. The lowest cost is 1 (index 2). The total cost = 1 + 1 = 2.
- In the third hiring round there are less than three candidates. We choose the worker from the remaining workers [2,4]. The lowest cost is 2 (index 0). The total cost = 2 + 2 = 4.
The total hiring cost is 4.
Constraints:
costs.length
<= 105costs[i]
<= 105k
, candidates
<= costs.length
不看 Discussion 根本看不懂這題在幹嘛= =
class Solution:
def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
head_workers = costs[:candidates]
tail_workers = costs[max(candidates, len(costs) - candidates):]
heapq.heapify(head_workers)
heapq.heapify(tail_workers)
ans = 0
next_head, next_tail = candidates, len(costs) - 1 - candidates
for _ in range(k):
if not tail_workers or head_workers and head_workers[0] <= tail_workers[0]:
ans += heapq.heappop(head_workers)
if next_head <= next_tail:
heapq.heappush(head_workers, costs[next_head])
next_head += 1
else:
ans += heapq.heappop(tail_workers)
if next_head <= next_tail:
heapq.heappush(tail_workers, costs[next_tail])
next_tail -= 1
return ans
Ron ChenMon, Jun 26, 2023