Problem 309918 · medium · Level 03 Linear Management & Searching

Spread Out the Routers

binary search on the answer · greedy

positions lists the (unsorted, distinct) spots along a corridor where a router may be mounted. You must mount exactly m routers, each at a different spot, and you want the closest pair of routers to be as far apart as possible. Return that largest achievable minimum distance.

Examples

Input:  positions = [1, 2, 3, 4, 7], m = 3
Output: 3
Explanation: mount at 1, 4 and 7.

Input:  positions = [5, 4, 3, 2, 1, 1000000000], m = 2
Output: 999999999

Input:  positions = [1, 2, 3], m = 3
Output: 1

Constraints

  • 2 <= m <= len(positions) <= 5 * 10**4
  • 0 <= positions[i] <= 10**9, all distinct
  • Required time: O(n log n + n log(max(positions))).

Goals

  • Binary search over a distance and verify with a greedy placement
  • Sort unsorted input before searching
Starting Python…