Minimize Max Distance to Gas Station
Pattern: Binary search on the answer
Guess a largest gap D. A gap of g then needs ceil(g / D) - 1 new stations. A bigger D needs fewer, so binary search D on real numbers, stopping after enough halvings.
The problem
Gas stations stand at whole-number positions on a line, given in increasing order. You may add k new stations at any
positions, including non-whole ones. Return the smallest possible value of the largest distance between neighbouring
stations. For example, stations [1, 2, …, 10] with k = 9 give 0.5.
The function name minmaxGasDist matches LeetCode, where this problem needs a premium account. Use the link above for
the exact statement and limits. LeetCode accepts answers within 10⁻⁶. So that all three languages print the same text,
this guide's tests print the answer with 4 decimals.
Think first
- If the largest gap must be at most
D, how many new stations does a gap of lengthgneed? - Does a bigger
Dneed more stations or fewer? - The answer is a real number. When does the search stop?
Hints
Brute force, and why it fails
Add stations one by one, each into the gap whose current piece is largest, using a heap: O(k log n). That works but is
slow when k is large. Binary search on D is O(n × 100).
The key insight
Binary search also works on real numbers. Instead of stopping when lo meets hi, stop after a fixed number of
halvings, because each one doubles the precision.
Dry run
| lo | 0 |
|---|---|
| hi | 6 |
stations = [1, 7] and k = 2 new stations. There is one gap of 6. D lies between 0 and 6.
The plan
lo = 0, hi = last - first
repeat 100 times:
mid = (lo + hi) / 2
needed = sum over gaps g of ceil(g / mid) - 1
if needed <= k: hi = mid
else: lo = mid
return hi
Complexity
- Time
O(n × 100)- Space
O(1)
100 halvings, each counting stations over the n - 1 gaps.
Edge cases
k = 0: the answer is the largest existing gap.- One big gap, as in
[0, 10]withk = 0: 10. - Equal gaps: each new station splits the current largest gap.
I've built my logic, show the code
Java
class Solution {
public double minmaxGasDist(int[] stations, int k) {
double lo = 0, hi = stations[stations.length - 1] - stations[0];
for (int iter = 0; iter < 100; iter++) { // each round halves the gap between lo and hi
double mid = (lo + hi) / 2;
if (needed(stations, mid) <= k) hi = mid; // a largest gap of mid is reachable: try smaller
else lo = mid;
}
return hi;
}
private long needed(int[] stations, double d) {
long count = 0;
for (int i = 1; i < stations.length; i++) {
double gap = stations[i] - stations[i - 1];
count += (long) Math.ceil(gap / d) - 1; // new stations so that every piece is at most d
}
return count;
}
}C++
class Solution {
public:
double minmaxGasDist(vector<int>& stations, int k) {
double lo = 0, hi = stations.back() - stations[0];
for (int iter = 0; iter < 100; iter++) { // each round halves the gap between lo and hi
double mid = (lo + hi) / 2;
if (needed(stations, mid) <= k) hi = mid; // a largest gap of mid is reachable: try smaller
else lo = mid;
}
return hi;
}
long long needed(vector<int>& stations, double d) {
long long count = 0;
for (size_t i = 1; i < stations.size(); i++) {
double gap = stations[i] - stations[i - 1];
count += static_cast<long long>(ceil(gap / d)) - 1; // new stations so every piece is at most d
}
return count;
}
};Python
import math
class Solution:
def minmaxGasDist(self, stations: list[int], k: int) -> float:
lo, hi = 0.0, float(stations[-1] - stations[0])
for _ in range(100): # each round halves the gap between lo and hi
mid = (lo + hi) / 2
if self.needed(stations, mid) <= k:
hi = mid # a largest gap of mid is reachable: try smaller
else:
lo = mid
return hi
def needed(self, stations: list[int], d: float) -> int:
return sum(math.ceil((b - a) / d) - 1 for a, b in zip(stations, stations[1:])) # pieces at most dCommon mistakes
- Using
floor(g / D)as the count, which is one too many whenDdividesgexactly. - Looping while
lo < hiwith real numbers, which may never stop. - Returning
lo, which is a value that does not work;hialways does.