Parcel-delivery app~30 min2s · 256 MBtarget O((c + k) log c) time, O(c) spaceclassic twin: lc-2462heaps
A parcel-delivery app hires couriers from a waiting list. Each courier asks for a fee. The list is in the order of sign-up, so the front of the list waited the longest and the back signed up most recently.
The app runs k hiring rounds. In each round it looks only at the c couriers at the front and the c at the back of the list, and hires the cheapest of them. A list can hold 100,000 couriers, and c can be large, so scanning the candidates in every round is too slow.
Write total_hiring_cost(costs, k, candidates).
costs[i] is the fee of the courier at position i of the list. Positions start at 0.k rounds, look at the first candidates couriers still on the list and the last candidates couriers still on the list. If fewer than 2 × candidates couriers are left, all of them are candidates, and none is counted twice.k fees. It can pass the range of an int.Input: costs = [30, 14, 22, 9, 17, 9, 25], k = 3, candidates = 2
Output: 40Keep the front candidates in a left min-heap and the back candidates in a right min-heap. An entry is a fee and a position. The workers between the heaps wait in the middle: when a heap loses a worker, the next one from the middle joins it.
| Round | Left heap (fee, position) | Right heap | Hired | Joins from the middle |
|---|---|---|---|---|
| 1 | (14, 1), (30, 0) | (9, 5), (25, 6) | 9 (position 5, right) | position 4 (fee 17), to the right heap |
| 2 | (14, 1), (30, 0) | (17, 4), (25, 6) | 14 (position 1, left) | position 2 (fee 22), to the left heap |
| 3 | (22, 2), (30, 0) | (17, 4), (25, 6) | 17 (position 4, right) | position 3 (fee 9), to the right heap |
The fees are 9, 14 and 17, so the total is 40.
Input: costs = [3, 2, 3, 3], k = 2, candidates = 1
Output: 5Only the ends are candidates: 3 at position 0 and 3 at position 3. They tie, so position 0 is hired. Then the ends are 2 and 3, and the 2 is hired. The total is 5.
Input: costs = [8, 3, 6], k = 3, candidates = 5
Output: 17There are fewer than 2 × 5 couriers, so everyone is a candidate every round. The fees are hired in order: 3, 6 and 8.
1 ≤ length of costs ≤ 10^5, and 1 ≤ costs[i] ≤ 10^91 ≤ k ≤ length of costs1 ≤ candidates ≤ 10^5Scanning all 2c candidates in each of k rounds costs 2c × k: for c = 50,000 and k = 50,000 that is 5 × 10^9 steps. Removing a worker from a list also costs a shift of up to n places.
Two heaps hold the candidates, so each hire costs about log c steps. Fees reach 10^9 and k reaches 10^5, so the total can reach 10^14 and needs a 64-bit integer.