Minimize Maximum Distance Between Gas Stations
Minimize Maximum Distance Between Gas Stations is an answer-space optimization problem on a number line. You are given sorted station positions and allowed to add k new stations at fractional coordinates. The objective is to minimize the largest gap between adjacent stations after placements are made optimally.
The accepted method is binary search on the maximum allowed gap D. For each candidate D, compute how many new stations are needed so every original gap is split into pieces no larger than D. If required stations are within budget k, D is feasible and you search smaller; otherwise search larger. Continue until numerical precision reaches the required tolerance.
Judge checks include simple two-station layouts, uneven spacing, zero-addition cases, and precision-sensitive scenarios where floating-point handling must be careful. Return a numeric answer compatible with tolerance-based comparison. Core correctness depends on monotonic feasibility and accurate station-count formulas per gap, especially for exact-divisible distances where off-by-one rounding mistakes can silently shift results.
Precision management matters: stop binary search when interval width is below tolerance, and compute required station counts with mathematically correct floor/ceil behavior per gap. Small rounding mistakes can shift feasibility decisions near boundaries, causing off-by-one station requirements and failing strict floating-point checks.
Examples
Adding stations at positions 4 and 7 results in gaps of at most 3.
Adding 3 stations evenly between existing ones can make all distances at most 1.
Adding one station at position 5.5 minimizes the maximum gap to 4.5.
Algorithm Flow

Best Answers
class Solution {
public double minimize_max_distance(int[] stations, int k) {
double low = 0, high = stations[stations.length - 1] - stations[0];
for (int i = 0; i < 100; i++) {
double mid = (low + high) / 2;
if (check(mid, stations, k)) high = mid;
else low = mid;
}
return high;
}
private boolean check(double d, int[] stations, int k) {
int count = 0;
for (int i = 0; i < stations.length - 1; i++) {
count += (int)((stations[i+1] - stations[i]) / d);
}
return count <= k;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this problem.
