Social feed~15 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-1029greedy · sorting
You work on the job-matching feature of a social app. A company has invited 2n candidates to an interview day and has two offices, A and B. Exactly n candidates must go to each office.
Each candidate has a travel cost to office A and another to office B, in units. Your team lead asks: "How should we split the candidates so that the total travel cost is as low as possible?"
Write lowest_total_cost(costs).
costs[i] is a pair [cost_a, cost_b]: the travel cost of candidate i to office A and to office B.2n. Exactly n candidates go to office A and n go to office B.Input: costs = [[30, 20], [200, 300], [100, 110], [400, 50]]
Output: 370For each candidate, look at cost_a - cost_b: how much more office A costs than office B. Sort by that number. The two candidates with the smallest numbers go to A, the rest to B.
| Candidate | cost_a | cost_b | cost_a - cost_b | Office |
|---|---|---|---|---|
[200, 300] |
200 | 300 | -100 | A |
[100, 110] |
100 | 110 | -10 | A |
[30, 20] |
30 | 20 | 10 | B |
[400, 50] |
400 | 50 | 350 | B |
The total is 200 + 100 + 20 + 50 = 370.
Input: costs = [[5, 5], [7, 7]]
Output: 12Every split costs 5 + 7 = 12, because both offices cost the same for each candidate.
Input: costs = [[2, 7], [1, 2]]
Output: 4Candidate 0 goes to A for 2, and candidate 1 goes to B for 2. Sending candidate 1 to A and candidate 0 to B would cost 8.
2 ≤ len(costs) ≤ 100,000, and the length is even1 ≤ cost_a, cost_b ≤ 1,000,000There can be 100,000 candidates. Choosing which half goes to office A has about 10^30100 possibilities. A sort costs about 1.7 million steps and one pass costs 100,000 more. The total is at most 10^11 here, so use a 64-bit number.