2462. Total Cost to Hire K Workers
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
ksessions and hire exactly one worker in each session. - In each hiring session, choose the worker with the lowest cost from either the first
candidatesworkers or the lastcandidatesworkers. 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 the4thworker because they have the lowest cost[3,2,7,7,**1**,2]. - In the second hiring session, we will choose
1stworker because they have the same lowest cost as4thworker but they have the smallest index[3,**2**,7,7,2]. Please note that the indexing may be changed in the process.
- For example, if
- 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 exactly k workers.
Constraints:
1 <= costs.length <= 10**51 <= costs[i] <= 10**51 <= k, candidates <= costs.length
Reevaluate¶
- A find min problem: Heap, Min Binary Tree
- We only need to find the lowest cost in first
cost[0:candidates]and lastcost[len-1 - candidates : len], so we could used some dynamic left right pointer and a: Heap
Solving with heap¶
- Create a
leftheap andrightheap - Push
cost[0:candidates]toleftheap andcost[len-1 - candidates : len]torightheap - Pop ether head of
leftandrightheap then push next correspond from cost table back to the heap - Run it
ktime
Actual code¶
class Solution:
def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
left = []
right = []
for value in costs[:candidates]:
heapq.heappush(left, value)
for value in costs[max(candidates, len(costs) - candidates):]:
heapq.heappush(right, value)
pointerLeft = candidates - 1
pointerRight = len(costs) - candidates
total = 0
for i in range(k):
if left == [] and right == []:
break
if left == []:
total += heapq.heappop(right)
continue
elif right == []:
total += heapq.heappop(left)
continue
if left[0] <= right[0]:
total += heapq.heappop(left)
if pointerLeft + 1 < pointerRight:
pointerLeft += 1
heapq.heappush(left, costs[pointerLeft])
else:
total += heapq.heappop(right)
if pointerLeft < pointerRight - 1:
pointerRight -= 1
heapq.heappush(right, costs[pointerRight])
return total
Last update :
October 13, 2023
Created : August 16, 2023
Created : August 16, 2023