HardBinary SearchArrayGreedy

Minimize Max Distance to Gas Station

LeetCode
1 approach, code in all languages

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
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now