Minimize Max Distance to Gas Station - Problem

You are given an integer array stations that represents the positions of 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.

Input & Output

Example 1 — Basic Case
$ Input: stations = [1,3,6,10], k = 1
Output: 3.0
💡 Note: Initial gaps are [2,3,4]. Adding one station optimally in the gap of 4 (between 6 and 10) at position 8 gives gaps [2,3,2,2]. Maximum gap is 3.0.
Example 2 — Multiple Additions
$ Input: stations = [23,24,36,39,46,56,57,65,84,98], k = 1
Output: 14.0
💡 Note: Largest gap is 84-65=19. Adding one station at 74.5 splits it into two gaps of 9.5 each. New maximum gap becomes 14 (between 46 and 56).
Example 3 — Minimum Input
$ Input: stations = [1,2], k = 1
Output: 0.5
💡 Note: Initial gap is 1. Adding one station at 1.5 creates two gaps of 0.5 each. Maximum gap is 0.5.

Constraints

  • 2 ≤ stations.length ≤ 2000
  • 0 ≤ stations[i] ≤ 108
  • stations is sorted in a strictly increasing order
  • 1 ≤ k ≤ 106

Visualization

Tap to expand
Minimize Max Distance to Gas Station INPUT 1 3 6 10 d=2 d=3 d=4 stations = [1,3,6,10] k = 1 Gap Analysis: 1-3: 2 3-6: 3 6-10: 4 Max gap = 4 (needs split) ALGORITHM STEPS 1 Binary Search Setup lo=0, hi=max_gap=4 2 Check mid = 2.0 Stations needed: 0+1+1=2 2 > k=1, too small! 3 Check mid = 3.0 Stations needed: 0+0+1=1 1 == k, valid! 4 Converge to Answer Binary search narrows to optimal penalty count(gap, mid) = ceil(gap/mid) - 1 FINAL RESULT 1 3 6 10 NEW @8 2 3 2 2 OUTPUT 3.0 Max distance reduced from 4 to 3 Verification: OK All gaps <= 3.0 Key Insight: Binary search on the answer! Instead of deciding WHERE to place stations, search for the minimum penalty value. For each candidate penalty, count stations needed to achieve it. If count <= k, it's feasible. TutorialsPoint - Minimize Max Distance to Gas Station | Binary Search Approach
Asked in
Google 25 Amazon 18
28.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen