MediumNo. 2462

Total Cost to Hire K Workers — LeetCode 2462 Python Solution

Topics
Array, Two Pointers, Simulation, Heap (Priority Queue)
On a study list
LeetCode 75
Reading time
5 min

The 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.

Example

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.

Python solution

PythonSolution
class Solution:
    def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
        n = len(costs)
        if candidates * 2 >= n:
            return sum(sorted(costs)[:k])
        pq = []
        for i, c in enumerate(costs[:candidates]):
            heappush(pq, (c, i))
        for i in range(n - candidates, n):
            heappush(pq, (costs[i], i))
        heapify(pq)
        l, r = candidates, n - candidates - 1
        ans = 0
        for _ in range(k):
            c, i = heappop(pq)
            ans += c
            if l > r:
                continue
            if i < l:
                heappush(pq, (costs[l], l))
                l += 1
            else:
                heappush(pq, (costs[r], r))
                r -= 1
        return ans

Complexity

Time
O(n × log n)
Space · auxiliary
O(n)

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2462. Total Cost to Hire K Workers is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2462. Total Cost to Hire K Workers?

LeetCode 2462. Total Cost to Hire K Workers is rated Medium on LeetCode.

What is the time complexity of LeetCode 2462. Total Cost to Hire K Workers?

The Python solution on this page runs in O(n × log n).

What is the space complexity of LeetCode 2462. Total Cost to Hire K Workers?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 2462. Total Cost to Hire K Workers cover?

LeetCode 2462. Total Cost to Hire K Workers is tagged Array, Two Pointers, Simulation and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.