Problem Description
Given an array of gas station positions along the x-axis and an integer k, add k new gas stations (which can be placed anywhere, not necessarily at integer positions) such that the maximum distance between any two adjacent stations is minimized. The answer must be accurate within 10^-6.
Key Insights
- The optimal "penalty" (i.e., the maximum distance between adjacent stations after placement) can be found using binary search over a continuous distance range.
- For each candidate distance (mid), simulate the number of gas stations required by iterating over each adjacent station gap and calculating:
- stations_required = ceil(gap / mid) - 1
- If the total number of required additional stations is less than or equal to k, then mid is a feasible candidate; otherwise, it is too small.
- Continue the binary search until the gap between low and high is within the desired tolerance (1e-6).
Space and Time Complexity
Time Complexity: O(n * log(max_gap/precision)), where n is the number of stations. Space Complexity: O(1) (ignoring input storage)
Solution
We use binary search over the possible maximum distances. The algorithm sets low = 0 and high = the maximum gap between adjacent stations. For a candidate distance mid, we count how many new stations are required for all gaps by computing ceil(gap / mid) - 1. If the total required is within k, we try a smaller candidate; otherwise, we increase the candidate distance. This approach efficiently zooms into the minimum possible maximum distance (penalty).