HardBinary SearchArrayGreedy

Minimize Max Distance to Gas Station

1 approach, code in every language

Problem description

Gas stations sit along a straight highway at strictly increasing positions given in an array. You may add k brand-new stations anywhere on the highway, including at fractional positions between existing ones. After placing them, the penalty is the largest distance between two neighboring stations.

Distribute the k new stations to make that largest neighboring gap as small as possible, and return the resulting minimum possible maximum distance. Because positions are real numbers, the answer is a decimal value that you approximate to within a small tolerance.

Example 1

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

Output: 0.50000

There are nine unit gaps and nine stations to place. Dropping one station in the middle of each gap halves every gap to 0.5, which becomes the largest distance.

Example 2

Input: stations = [1,2,3,10], k = 2

Output: 2.33333

The dominant gap is the stretch of length 7 between 3 and 10. Placing both new stations inside it splits that stretch into three equal parts of 7/3, which outweighs the two unit gaps.

Constraints

  • 2 <= stations.length <= 10^4
  • 0 <= stations[i] <= 10^8
  • stations is sorted in strictly increasing order
  • 1 <= k <= 10^6

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free