#2462

Total Cost to Hire K Workers

Medium
ArrayTwo PointersHeap (Priority Queue)SimulationHeap (Priority Queue)Two Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution uses two min-heaps to efficiently track the lowest cost workers from both ends of the array. This allows us to quickly find and hire the cheapest worker in each session without scanning the entire array repeatedly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize two min-heaps, one for the left candidates and one for the right candidates.
  2. 2Step 2: Populate the heaps with the first 'candidates' workers from the left and the last 'candidates' workers from the right.
  3. 3Step 3: For each hiring session, compare the top of both heaps, hire the worker with the lowest cost, and update the total cost. If a worker is hired from one side, push the next worker from that side into the corresponding heap.
solution.py31 lines
1import heapq
2
3def totalCost(costs, k, candidates):
4    total_cost = 0
5    n = len(costs)
6    left_heap, right_heap = [], []
7    hired = [False] * n
8
9    for i in range(min(candidates, n)):
10        heapq.heappush(left_heap, (costs[i], i))
11    for i in range(max(0, n - candidates), n):
12        heapq.heappush(right_heap, (costs[i], i))
13
14    for _ in range(k):
15        left_cost = left_heap[0] if left_heap else (float('inf'), -1)
16        right_cost = right_heap[0] if right_heap else (float('inf'), -1)
17
18        if left_cost[0] <= right_cost[0]:
19            total_cost += left_cost[0]
20            hired[left_cost[1]] = True
21            heapq.heappop(left_heap)
22            if left_cost[1] + candidates < n:
23                heapq.heappush(left_heap, (costs[left_cost[1] + candidates], left_cost[1] + candidates))
24        else:
25            total_cost += right_cost[0]
26            hired[right_cost[1]] = True
27            heapq.heappop(right_heap)
28            if right_cost[1] - candidates >= 0:
29                heapq.heappush(right_heap, (costs[right_cost[1] - candidates], right_cost[1] - candidates))
30
31    return total_cost

Complexity note: The time complexity is O(n log n) due to the use of heaps for managing the workers, where each insertion and extraction operation takes logarithmic time. The space complexity is O(n) because we store the workers in heaps.

  • 1Using heaps allows us to efficiently manage and retrieve the lowest cost workers.
  • 2Maintaining two heaps for both ends of the array helps in managing candidates effectively.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.