Minimize Max Distance to Gas Station Problem
Description
LeetCode Problem 774.
You are given an integer array stations that represents the positions of the gas stations on the x-axis. You are also given an integer k.
You should add k new gas stations. You can add the stations anywhere on the x-axis, and not necessarily on an integer position.
Let penalty() be the maximum distance between adjacent gas stations after adding the k new stations.
Return the smallest possible value of penalty(). Answers within 10^-6 of the actual answer will be accepted.
Example 1:
Input: stations = [1,2,3,4,5,6,7,8,9,10], k = 9
Output: 0.50000
Example 2:
Input: stations = [23,24,36,39,46,56,57,65,84,98], k = 1
Output: 14.00000
Constraints:
10 <= stations.length <= 20000 <= stations[i] <= 10^8stationsis sorted in a strictly increasing order.1 <= k <= 10^6
Solution
Approach: Binary Search on the Answer
Turn the question around: for a given limit x, how many new stations do we need so that no gap is longer than x? A gap of length g has to be cut into ceil(g / x) pieces, which takes ceil(g / x) - 1 new stations, and the gaps are independent, so we just add these counts up.
That count only goes down as x grows. So "can k stations bring the penalty down to x?" is false for small x and true from some point on, and the answer is exactly that point. Binary search for it on real numbers:
- start with
lo = 0andhi= the whole distance from the first to the last station (always enough); - take
mid = (lo + hi) / 2; if at mostkstations are needed, the answer is at mostmid, so sethi = mid, otherwise setlo = mid; - stop when
hi - lois below1e-7and returnhi.
Trying to place the stations directly (for example, always splitting the currently largest gap) needs a priority queue and k steps, and k can be 106. The binary search instead needs only about 50 rounds, because the search range shrinks from 108 to 10-7 by halving.
Stop on a width a bit below the allowed error of 10-6, so the returned hi is safely within it. Use an absolute width, not a relative one: the answer can be tiny (ten stations one unit apart plus a million new stations give a penalty near 10-5).
Complexity: O(n · log(D / ε)) time, where n is the number of stations, D the total distance and ε = 10-7 (about 50 rounds of O(n) each). O(1) extra space.
import math
class Solution:
def minmaxGasDist(self, stations: List[int], k: int) -> float:
def needed(limit: float) -> int:
# A gap of length g needs ceil(g / limit) - 1 new stations so that no piece is longer than limit.
return sum(math.ceil((b - a) / limit) - 1 for a, b in zip(stations, stations[1:]))
lo, hi = 0.0, float(stations[-1] - stations[0])
while hi - lo > 1e-7:
mid = (lo + hi) / 2
if needed(mid) <= k:
hi = mid # k stations are enough: try a smaller penalty
else:
lo = mid
return hi