VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimize-the-maximum-distance-between-adjacent-points-after-adding-k-points-anywhere-in-between/

⇱ Minimize the maximum distance between adjacent points after adding K points anywhere in between - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimize the maximum distance between adjacent points after adding K points anywhere in between

Last Updated : 25 Aug, 2025

Given an array stations[] of integers representing the position of N points along a straight line and an integer k, the task is to find the minimum value of the maximum distanced between adjacent gas stations after adding K more gas stations anywhere in between, not necessarily on an integer position.
Note: Stations are in strictly increasing order

Examples:

Input: stations[] = {1, 2, 3, 4, 5}, K = 2
Output: 1.00
Explanation: Since all gaps are already equal (1 unit each), adding extra stations in between does not reduce the maximum distance.

Input: stations[] = {3, 6, 12, 19, 33}, K = 3
Output: 6.00
Explanation: The largest gap is 14 (between 19 and 33). Adding 2 stations there splits it into ≈4.67. The next largest gap is 7 (between 12 and 19). Adding 1 station splits it into 3.5. Now the maximum gap left is 6.

[Expected Approach] Binary Search - O(n*log m) Time and O(1) Space :

The given problem can be solved by using Binary Search. The idea is to perform a binary search on the value D in the range [0, 108] where D represents the value of the maximum distance between the adjacent points after adding K points.

Step By Step Implementation:

  • Initialize variables, low = 1 and high = 108, where low represents the lower bound and high represents the upper bound of the binary search.
  • Create a function isPossible(), which returns the boolean value of whether it is possible to add K points in the array such that the maximum distance between adjacent points is D. It is based on the observation that for two adjacent points (i, j), the number of points required to be placed in their middle such that the maximum distance between them is D = (j -i)/D.
  • Therefore, traverse the range using the binary search algorithm discussed here, and if for the mid-value D in the range [X, Y], if isPossible(D) is false, then iterate in the upper half of the range i.e, [D, Y]. Otherwise, iterate on the lower half i.e, [X, D].
  • Iterate a loop until (high - low) > 10-6.
  • The value stored in low is the required answer.

Below is the implementation of the above approach:


Output
0.5

Time Complexity: O(N*log M), where the value of M is 1014.
Auxiliary Space: O(1)


Comment