Add K Streetlights at Integer Positions to Minimize the Longest Dark Stretch
Implement minMaxGap
A street has some streetlights already installed at integer positions, given sorted in
positions. You may add up to k new streetlights, each also at an integer position (any position is allowed, not only ones already listed). Find the placement that minimizes the longest stretch of road between any two consecutive streetlights (existing or new), and return that minimized length.
Because every position must be an integer, splitting one existing gap of length g into pieces no longer than a candidate length L takes a fixed, computable number of new lights: ⌈g / L⌉ - 1. That's what makes this version different from the classic continuous-position variant of this problem — no floating-point search is needed, since the cost of any candidate stretch length is an exact integer.
The total new-light cost only ever decreases (or stays flat) as the candidate stretch length grows, which makes this a binary search on the answerBinary Search on the AnswerInstead of searching a sorted array, the search runs directly over the space of possible answers (here, every candidate stretch length). It works whenever "is this candidate good enough?" is monotonic — once a candidate works, every larger candidate keeps working too. — search directly over candidate stretch lengths rather than trying every possible placement.
Example 1:
Input: positions = [0,10,20], k = 2
Output: 5
Example 2:
Input: positions = [1,5,9], k = 1
Output: 4
Example 3:
Input: positions = [0,100], k = 9
Output: 10
+ 5 hidden test cases run on Submit.
Constraints:
- ●
2 ≤ number of existing streetlights ≤ 10⁴ - ●
0 ≤ positions[i] ≤ 10⁶, given in strictly increasing order - ●
0 ≤ k ≤ 10⁴ — the number of new streetlights that may be added - ●
Every streetlight (existing or new) must sit at an integer position
positions =
[0, 10, 20]
k =
2