Minimise max distance to gas stations

Binary Search FAQs Hard
  • Fun Fact: This problem embodies the concept of binary search, which can be used in real-life application route planning software
  • Tools like Google Maps, Waze or Apple Maps often have to solve similar problems when determining optimal locations for refueling or rest stops during a trip
  • The goal is to minimize the longest distance between stops, ensuring that the user's gas tank doesn't run out
  • Therefore, developers of such apps need to design and implement efficient algorithms to provide the best service to their users

Given a sorted array arr of size n, containing positive integer positions of n gas stations on the X-axis, and an integer k, place k new gas stations on the X-axis. The new gas stations can be placed anywhere on the non-negative side of the X-axis, including non-integer positions. Let dist be the maximum distance between adjacent gas stations after adding the k new gas stations. Find the minimum value of dist.

Examples:

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

Output: 0.50000

Explanation: One of the possible ways to place 10 gas stations is [1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8, 8.5, 9, 9.5, 10]. Thus the maximum difference between adjacent gas stations is 0.5. Hence, the value of dist is 0.5. It can be shown that there is no possible way to add 10 gas stations in such a way that the value of dist is lower than this.

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

Output: 1.00000

Explanation: One of the possible ways to place 1 gas station is [1, 1.5, 2, 3, 4, 5, 6, 7, 8, 9, 10]. Thus the maximum difference between adjacent gas stations is still 1. Hence, the value of dist is 1. It can be shown that there is no possible way to add 1 gas station in such a way that the value of dist is lower than this. 

Input: n = 10, arr= [3, 6, 12, 19, 33, 44, 67, 72, 89, 95], k = 2

Constraints

  • 10 <= n <= 5000 
  • 0 <= arr[i] <= 10
  • 0 <= k <= 105

Hints

  • For a given dist, calculate the number of new gas stations required to ensure that no gap exceeds dist. Sum the required gas stations across all gaps. If the total gas stations required is less than or equal to k, the given dist is feasible.
  • "If dist is feasible (i.e., the required gas stations ≤k), search for a smaller dist (high=mid). If dist is not feasible, search for a larger dist (low=mid+ϵ), where ϵ ensures precision for floating-point values."

Company Tags

Rakuten Alibaba Broadcom Zynga Shopify Docker MongoDB Electronic Arts Chewy American Express Zomato Deloitte Splunk Snowflake Epic Games Seagate Technology HCL Technologies Activision Blizzard Epic Systems Intel NVIDIA Robinhood Oracle Micron Technology JPMorgan Chase Google Microsoft Amazon Meta Apple Netflix Adobe