oneby7

Binary Search Searching the answer

252. Minimize Max Distance to Gas Station

Hard

Gas stations stand along a straight road. stations[i] is the position of the i-th station, in miles from the start of the road, and the positions are in increasing order.

You will build k new stations. Each one can go anywhere on the road, at any real position, not only at whole miles. After that, look at the distance between every two neighbouring stations, old and new. Return the smallest possible value of the largest of these distances.

The answer is a real number. An answer counts as right when it is within 10−6 of the expected answer, or, for an expected answer larger than 1, within 10−6 times that answer.

Example 1

Input: stations = [0, 10, 14, 30], k = 3

Output: 5.333333333333333

Explanation: Build two stations between 14 and 30, at about 19.33 and 24.67, which cuts that stretch into three pieces of 16/3 ≈ 5.33 miles. Build the third at 5, between 0 and 10. The distances are 5, 5, 4 and three times 16/3, so the largest is 16/3.

Example 2

Input: stations = [0, 5, 10, 15, 20], k = 3

Output: 5

Explanation: There are four gaps of 5 miles and only three new stations, so at least one gap of 5 stays as it is.

Example 3

Input: stations = [0, 1000000000], k = 1000000

Output: 999.999000001

Explanation: The million new stations cut the road into 1000001 equal pieces of 109 / 1000001 miles.

Check your understanding

Work out the answer for this input before you write any code.

stations = [0, 12, 14], k = 2

Constraints

  • 2 ≤ stations.length ≤ 105
  • 0 ≤ stations[i] ≤ 109
  • stations is strictly increasing.
  • 1 ≤ k ≤ 106

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.