Place Sensors on a Track to Maximize the Smallest Gap Between Them

Implement maxMinGap

Given positions, the sorted locations of every mounting point along a straight track, and an integer k, choose k of those points to install sensors so that the smallest distance between any two installed sensors is as large as possible. Return that largest possible minimum distance. Unlike most binary-search-on-answer problems, this one maximizes the answer instead of minimizing it — but the same monotonic structure still applies, just flipped: if k sensors can all be placed at least d apart, the same greedy placement (always jump to the next point at least d away from the last one placed) trivially works for any smaller d too. That "easier for a smaller gap" relationship is exactly what a binary search on the answerBinary Search on the AnswerThe search runs directly over the space of candidate answers rather than over the array's values. It applies whenever "is this candidate good enough?" is monotonic in one direction — here, achievability only ever improves as the candidate gap shrinks. needs — search the candidate gaps directly, keeping the largest one that still manages to place every sensor.

Example 1:

Input: positions = [3,6,9,12,15], k = 3

Output: 6

Example 2:

Input: positions = [2,5,8,9,14], k = 2

Output: 12

Example 3:

Input: positions = [7,14,21,28,35], k = 3

Output: 14

+ 5 hidden test cases run on Submit.

Constraints:

  • 2 ≤ number of mounting points ≤ 10⁵
  • 0 ≤ positions[i] ≤ 10⁹, given in strictly increasing order
  • 2 ≤ k ≤ number of mounting points

positions =

[3, 6, 9, 12, 15]

k =

3