Home life · Updated
Total Cost to Hire K Workers: Two Heaps, One Answer
Quick answer The total cost to hire k workers is found by simulating the hiring rounds with two min-heaps: one holds the first `candidates` costs, the other the last `candidates`. Each round you hire the cheaper of the two heap tops, add that cost to a running total, and refill that side's heap from the middle of the array.
This is the classic “Total Cost to Hire K Workers” problem: you’re given an array of hiring costs, a number of workers to hire (k), and a window size (candidates), and each hiring round only the first and last `candidates` workers are available. The two-heap approach answers it in roughly O((k + n) log n) time instead of the O(n·k) you’d get by rescanning the array every round.
Run the Hiring Rounds With Two Min-Heaps
- Split the ends into two pools. Put the first `candidates` costs into a left min-heap and the last `candidates` costs into a right min-heap. Keep two pointers: `nextLeft` starts at `candidates` and `nextRight` starts at `n – candidates – 1`.
- Handle the small-array case first. If `n` is at most `2 * candidates`, the two windows overlap, so push every cost into the left heap alone, leave the right heap empty, and skip all refilling.
- Compare the two heap tops. Each round, look at the smallest cost in the left heap and the smallest in the right heap. Hire whichever is smaller; on a tie, either choice gives the same total.
- Add the hired cost to the total. Keep a running sum and increment a hired-worker counter until it reaches k.
- Refill from the middle. If you hired from the left heap and `nextLeft` has not passed `nextRight`, push `costs[nextLeft]` into the left heap and advance the pointer. Do the mirror-image refill for the right heap.
- Stop at k hires. The running sum after k rounds is the answer. Never keep hiring after the counter is full, even if heaps still hold workers.
Set Up the Pools Before Round One
The setup decides everything, so get the boundaries exact. For an array of length n with window size c, the left pool covers indices 0 through c-1 and the right pool covers indices n-c through n-1. The workers between those windows sit out until a hire on their side of the array pulls one of them in.
Watch the overlap boundary closely. When n equals exactly 2*c, the two windows meet with no gap, and pointers start adjacent rather than overlapping. When n is smaller than 2*c, the windows would double-count workers, which is exactly why step 2 collapses everything into one heap. Double-counted workers get hired twice and inflate the total.
Trace Six Costs and Three Hiring Rounds
Take costs = [10, 3, 8, 1, 5, 12], k = 3, candidates = 2. The array has 6 entries and 2 * 2 = 4 is less than 6, so two pools apply. Left pool: {10, 3}. Right pool: {5, 12}. The middle workers, 8 and 1, wait at indices 2 and 3.
Round 1: the left heap’s top is 3 and the right heap’s top is 5, so hire 3. Total so far: 3. Refill the left pool with costs[2] = 8, so left becomes {10, 8}.
Round 2: left top is 8, right top is 5, so hire 5. Total so far: 8. Refill the right pool with costs[3] = 1, so right becomes {12, 1}.
Round 3: left top is 8, right top is 1, so hire 1. Total: 3 + 5 + 1 = 9. Three workers are hired, so 9 is the answer. Notice the worker with cost 1 was unreachable in round 1 but became available exactly when the window slid to include them, which is the whole point of the refill step.
Where the Hiring Rounds Go Wrong
The most common wrong idea is that the answer is simply the sum of the k smallest costs in the whole array. That shortcut fails because each round only offers the workers inside the two windows, and a cheap worker buried in the middle may never become available before you finish hiring. The correct fact: the sum of the k cheapest costs is the answer only in the small-array case where n is at most 2*candidates, because then every worker sits in a single pool from the start.
Three bugs account for most wrong submissions. First, forgetting the tie rule: when both heap tops are equal, either hire is valid, so don’t add special-case logic that skips a round. Second, refilling the wrong side: if you hire from the left heap but push the replacement into the right heap, the window slides the wrong way and cheap middle workers stay hidden. Third, letting the pointers cross: once `nextLeft` passes `nextRight`, the middle is exhausted, and pushing again re-adds a worker who is already in a pool.
One more subtle trap: heaps must be min-heaps. Many languages default to max-heap behaviour (for example, Python’s heapq is a min-heap, but you must negate values by hand to simulate one in languages that only offer max-heaps). A max-heap in either pool hires the most expensive available worker every round.
Check Your Answer Against the Brute Force
The fastest way to verify your implementation is a slow reference version: each round, scan the first c and last c un-hired workers directly, take the minimum, mark that worker hired, and repeat k times. Run both versions on small random arrays (say, 8 to 12 costs, k between 1 and 5, candidates between 1 and 6) and confirm the totals match. Any disagreement points at your refill or overlap logic, not at the idea itself.
Also test the boundary inputs by hand: k equal to the array length (you hire everyone), candidates equal to 1 (one worker per side per round), and candidates large enough to cover the whole array (the single-pool case). If your code survives those three plus the random comparison, the two-heap logic is sound.
Related
- Total Population of Lagos: The Numbers and Why They Differ
- How to Fold Up a Total Gym for Storage
- How to Iron Clothes Free: 7 No-Cost Methods
Sources: general know-how. Menus and buttons can differ slightly by version. Spotted something out of date? Tell us.