Parcel-delivery app~30 min2s · 256 MBtarget O(n log n + n log R) time, O(n) spaceclassic twin: lc-1552binary-search-answer · greedy · sorting
A parcel-delivery app wants to open pickup lockers along one straight road. A survey found n possible spots, each at a distance in metres from the start of the road. The app will use lockers of them.
To serve as many neighbourhoods as possible, the lockers should be spread out. The app wants the smallest distance between any two chosen lockers to be as large as possible. What is that largest smallest distance?
Write max_min_gap(spots, lockers).
spots[i] is the distance of candidate spot i from the start of the road. All the spots are different.lockers of the spots. The gap of a choice is the smallest distance between two of the chosen spots.Input: spots = [1, 2, 8, 4, 9], lockers = 3
Output: 3Sort the spots: [1, 2, 4, 8, 9]. To check a gap d, place the first locker at the first spot, then each next locker at the first spot that is at least d further. The window [lo, hi) holds the gaps that might still work. The gap 9 (the spread 8, plus 1) is certainly too wide.
| Step | lo | hi | mid | lockers placed at mid | Decision |
|---|---|---|---|---|---|
| 1 | 1 | 9 | 5 | 2 (at 1 and 8) | 2 < 3, too wide, so hi = 5 |
| 2 | 1 | 5 | 3 | 3 (at 1, 4 and 8) | 3 >= 3, works, so lo = 4 |
| 3 | 4 | 5 | 4 | 2 (at 1 and 8) | 2 < 3, too wide, so hi = 4 |
| end | 4 | 4 | the first gap that is too wide is 4, so the answer is 3 |
With lockers at 1, 4 and 8, the smallest distance is 3.
Input: spots = [10, 20], lockers = 2
Output: 10Two lockers use both spots, so the gap is 10, the whole spread. That is the top of the range.
Input: spots = [5, 6, 7, 8], lockers = 4
Output: 1Using every spot gives a gap of 1, the smallest possible, because the spots are different whole numbers.
2 ≤ spots.length ≤ 100,000, all spots are different, in any order0 ≤ spots[i] ≤ 1,000,000,000 (metres along the road)2 ≤ lockers ≤ spots.lengthThere are astronomically many ways to choose the lockers, and trying gap sizes one by one from 1 costs about n × (the answer), which can be 10^9 × 10^5. Sorting costs n log n. One greedy pass checks a gap in n steps, and a binary search over gaps up to 10^9 needs about 30 passes.