Ride-hailing app~25 min2s · 256 MBtarget O(n log n) time, O(n) spacegreedy · sorting
A ride-hailing app serves a long road with milestone numbers. At this moment there are as many waiting riders as free drivers, and each position is a milestone number.
Your team lead says: "Give every rider exactly one driver, and every driver exactly one rider. Choose the pairs so that the total distance the drivers travel to their pickups is as small as it can be."
The distance between a rider at milestone a and a driver at milestone b is |a - b|. Several people can stand at the same milestone.
Write min_total_distance(riders, drivers).
riders[i] is the milestone of rider i, and drivers[j] is the milestone of driver j. The lists are not in any order.n.|rider - driver| over the n pairs.Input: riders = [8, 2, 6, 15], drivers = [12, 5, 1, 9]
Output: 6The code sorts both lists, then pairs the k-th rider from the left with the k-th driver from the left.
| k | Rider after sorting | Driver after sorting | Distance | Total so far |
|---|---|---|---|---|
| 0 | 2 | 1 | 1 | 1 |
| 1 | 6 | 5 | 1 | 2 |
| 2 | 8 | 9 | 1 | 3 |
| 3 | 15 | 12 | 3 | 6 |
The riders at 2, 6, 8 and 15 take the drivers at 1, 5, 9 and 12, and the total is 6.
Input: riders = [5], drivers = [5]
Output: 0The only rider and the only driver stand at the same milestone, so nobody travels.
Input: riders = [7, 7, 7], drivers = [1, 1, 1]
Output: 18Every pair is 6 apart, whatever the pairing, and 3 pairs make 18.
1 ≤ n ≤ 10^5, and both lists have length n0 ≤ riders[i], drivers[j] ≤ 10^9Trying every way to give the drivers to the riders means n! pairings. For n = 10 that is 3,628,800, and for n = 12 it is 479,001,600. At n = 10^5 it is far beyond any computer.
A faster idea must decide the pairs without trying them. Sorting costs O(n log n), which is about 1.7 × 10^6 steps for 10^5 people.
The sum can reach 10^5 × 10^9 = 10^14, so use a 64-bit integer for the total.