Minimize Max Distance to Gas Station

Add k gas stations on a number line to minimize the maximum gap — binary search on the answer with a greedy feasibility check.

Hard
Time O(n log(maxGap / eps)) Space O(1)
LeetCode
4 min read
binary-search

Problem#

Existing gas stations are on a number line. Add k more. Minimize the maximum gap between adjacent stations. Return that minimum gap (real-valued).

Examples#

  • stations = [1,2,3,4,5,6,7,8,9,10], k = 90.5

Constraints#

  • 1 <= stations.length, k <= 10^4. Real-valued answer.

Approach#

Binary search on the answer d (in [0, maxGap]). For each gap g, we need floor(g / d) extra stations to split it into intervals ≤ d. Feasible iff total extra ≤ k. Use real-valued search until hi - lo < 1e-6.

Solution#

Minimize Max Distance to Gas Station
class Solution {
public:
double minmaxGasDist(vector<int>& stations, int k) {
double lo = 0, hi = 1e8;
auto need = [&](double d) {
long long total = 0;
for (int i = 1; i < (int)stations.size(); ++i) {
total += (long long)((stations[i] - stations[i - 1]) / d);
}
return total;
};
for (int iter = 0; iter < 100 && hi - lo > 1e-6; ++iter) {
double mid = (lo + hi) / 2;
if (need(mid) > k) lo = mid;
else hi = mid;
}
return lo;
}
};

Editorial#

Continuous-domain binary search: instead of lo < hi, run a fixed number of iterations or until the precision threshold. Each iteration halves the range, so 50–100 iterations give ample precision.

Complexity#

  • Time: O(n × iterations).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.