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

• Last Updated : 26 May, 2022

Given an array arr[] of N 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 distance between adjacent points after adding K points anywhere in between, not necessarily on an integer position.

Examples:

Input: arr[] = {2, 4, 8, 10}, K = 1
Output: 2
Explanation: A point at position 6 can be added. So the new array of points become {2, 4, 6, 8, 10} and the maximum distance between two adjacent points is 2 which is minimum possible.

Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, K = 9
Output: 0.5

Approach: 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. Follow the steps below to solve the given problem:

• 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:

## C++

 `// C++ program for the above approach``#include ``using` `namespace` `std;` `// Function to check if it is possible``// to add K points such that the maximum``// distance between adjacent points is D``bool` `isPossible(``double` `D, ``int` `arr[],``                ``int` `N, ``int` `K)``{``    ``// Stores the count of point used``    ``int` `used = 0;` `    ``// Iterate over all given points``    ``for` `(``int` `i = 0; i < N - 1; ++i) {` `        ``// Add number of points required``        ``// to be placed between ith``        ``// and (i+1)th point``        ``used += (``int``)((arr[i + 1]``                       ``- arr[i])``                      ``/ D);``    ``}` `    ``// Return answer``    ``return` `used <= K;``}` `// Function to find the minimum value of``// maximum distance between adjacent points``// after adding K points any where between``double` `minMaxDist(``int` `stations[], ``int` `N, ``int` `K)``{``    ``// Stores the lower bound and upper``    ``// bound of the given range``    ``double` `low = 0, high = 1e8;` `    ``// Perform binary search``    ``while` `(high - low > 1e-6) {` `        ``// Find the middle value``        ``double` `mid = (low + high) / 2.0;` `        ``if` `(isPossible(mid, stations, N, K)) {` `            ``// Update the current range``            ``// to lower half``            ``high = mid;``        ``}` `        ``// Update the current range``        ``// to upper half``        ``else` `{``            ``low = mid;``        ``}``    ``}` `    ``return` `low;``}` `// Driver Code``int` `main()``{``    ``int` `arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };``    ``int` `K = 9;``    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr[0]);` `    ``cout << minMaxDist(arr, N, K);` `    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.math.BigDecimal;` `class` `GFG {` `    ``// Function to check if it is possible``    ``// to add K points such that the maximum``    ``// distance between adjacent points is D``    ``public` `static` `boolean` `isPossible(``double` `D, ``int` `arr[],``                                     ``int` `N, ``int` `K)``    ``{``        ``// Stores the count of point used``        ``int` `used = ``0``;` `        ``// Iterate over all given points``        ``for` `(``int` `i = ``0``; i < N - ``1``; ++i) {` `            ``// Add number of points required``            ``// to be placed between ith``            ``// and (i+1)th point``            ``used += (``int``) ((arr[i + ``1``] - arr[i]) / D);``        ``}` `        ``// Return answer``        ``return` `used <= K;``    ``}` `    ``// Function to find the minimum value of``    ``// maximum distance between adjacent points``    ``// after adding K points any where between``    ``public` `static` `double` `minMaxDist(``int` `stations[], ``int` `N, ``int` `K)``    ``{``      ` `        ``// Stores the lower bound and upper``        ``// bound of the given range``        ``double` `low = ``0``, high = 1e8;` `        ``// Perform binary search``        ``while` `(high - low > 1e-``6``) {` `            ``// Find the middle value``            ``double` `mid = (low + high) / ``2.0``;` `            ``if` `(isPossible(mid, stations, N, K)) {` `                ``// Update the current range``                ``// to lower half``                ``high = mid;``            ``}` `            ``// Update the current range``            ``// to upper half``            ``else` `{``                ``low = mid;``            ``}``        ``}``      ` `        ``// System.out.printf("Value: %.2f", low);``        ``return` `low;``    ``}` `    ``// Driver Code``    ``public` `static` `void` `main(String args[])``    ``{``        ``int` `arr[] = { ``1``, ``2``, ``3``, ``4``, ``5``, ``6``, ``7``, ``8``, ``9``, ``10` `};``        ``int` `K = ``9``;``        ``int` `N = arr.length;` `        ``System.out.printf(``"%.1f"``, minMaxDist(arr, N, K));``    ``}``}` `// This code is contributed by _saurabh_jaiswal.`

## Python3

 `# Python3 program for the above approach` `# Function to check if it is possible``# to add K points such that the maximum``# distance between adjacent points is D``def` `isPossible(D, arr, N, K) :` `    ``# Stores the count of point used``    ``used ``=` `0``;` `    ``# Iterate over all given points``    ``for` `i ``in` `range``(N ``-` `1``) :` `        ``# Add number of points required``        ``# to be placed between ith``        ``# and (i+1)th point``        ``used ``+``=` `int``((arr[i ``+` `1``] ``-` `arr[i]) ``/` `D);` `    ``# Return answer``    ``return` `used <``=` `K;` `# Function to find the minimum value of``# maximum distance between adjacent points``# after adding K points any where between``def` `minMaxDist(stations, N, K) :``    ` `    ``# Stores the lower bound and upper``    ``# bound of the given range``    ``low ``=` `0``; high ``=` `1e8``;` `    ``# Perform binary search``    ``while` `(high ``-` `low > ``1e``-``6``) :` `        ``# Find the middle value``        ``mid ``=` `(low ``+` `high) ``/` `2.0``;` `        ``if` `(isPossible(mid, stations, N, K)) :` `            ``# Update the current range``            ``# to lower half``            ``high ``=` `mid;` `        ``# Update the current range``        ``# to upper half``        ``else` `:``            ` `            ``low ``=` `mid;` `    ``return` `round``(low, ``2``);` `# Driver Code``if` `__name__ ``=``=` `"__main__"` `:` `    ``arr ``=` `[ ``1``, ``2``, ``3``, ``4``, ``5``, ``6``, ``7``, ``8``, ``9``, ``10` `];``    ``K ``=` `9``;``    ``N ``=` `len``(arr);` `    ``print``(minMaxDist(arr, N, K));``    ` `    ``# This code is contributed by AnkThon`

## C#

 `// C# program for the above approach``using` `System;` `public` `class` `GFG {` `    ``// Function to check if it is possible``    ``// to add K points such that the maximum``    ``// distance between adjacent points is D``    ``public` `static` `bool` `isPossible(``double` `D, ``int` `[]arr,``                                     ``int` `N, ``int` `K)``    ``{``      ` `        ``// Stores the count of point used``        ``int` `used = 0;` `        ``// Iterate over all given points``        ``for` `(``int` `i = 0; i < N - 1; ++i) {` `            ``// Add number of points required``            ``// to be placed between ith``            ``// and (i+1)th point``            ``used += (``int``) ((arr[i + 1] - arr[i]) / D);``        ``}` `        ``// Return answer``        ``return` `used <= K;``    ``}` `    ``// Function to find the minimum value of``    ``// maximum distance between adjacent points``    ``// after adding K points any where between``    ``public` `static` `double` `minMaxDist(``int` `[]stations, ``int` `N, ``int` `K)``    ``{``      ` `        ``// Stores the lower bound and upper``        ``// bound of the given range``        ``double` `low = 0, high = 1e8;` `        ``// Perform binary search``        ``while` `(high - low > 1e-6) {` `            ``// Find the middle value``            ``double` `mid = (low + high) / 2.0;` `            ``if` `(isPossible(mid, stations, N, K)) {` `                ``// Update the current range``                ``// to lower half``                ``high = mid;``            ``}` `            ``// Update the current range``            ``// to upper half``            ``else` `{``                ``low = mid;``            ``}``        ``}``      ` `        ``// Console.Write("Value: %.2f", low);``        ``return` `low;``    ``}` `    ``// Driver Code``    ``public` `static` `void` `Main(String []args)``    ``{``        ``int` `[]arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };``        ``int` `K = 9;``        ``int` `N = arr.Length;` `        ``Console.Write(``"{0:F1}"``, minMaxDist(arr, N, K));``    ``}``}`   `// This code is contributed by 29AjayKumar`

## Javascript

 ``

Output:

`0.5`

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

Alternate Approach: The problem boils down to minimizing the maximum distance K times. Every time, to get the maximum distance we can use max heap.

Step -1 : Iterate through the array elements and store the adjacent array element’s distances in a max heap.

Step-2 : For K times, poll the max element from the heap and add to the heap max/2, max/2 i.e., we’re each time reducing the maximum distance to two equal halves.

Step-3 : Return the max element after iterating for K times.

Below is the implementation of the above approach:

## C++

 `#include``using` `namespace` `std;` `int` `main()``{``    ``int` `arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };``    ``int` `K = 9;``    ``int` `N = ``sizeof``(arr)/``sizeof``(arr[0]);`` ` `    ``// Max heap initialisation``    ``priority_queue<``float``>pq;``  ` `    ``// Add adjacent distances to max heap``    ``for` `(``int` `i = 1; i < N; i++) {``        ``pq.push((``float``)arr[i] - (``float``)arr[i - 1]);``    ``}`` ` `    ``// For K times, half the maximum distance``    ``for` `(``int` `i = 0; i < K; i++) {``        ``float` `temp = pq.top();``        ``pq.pop();``        ``pq.push(temp / 2);``        ``pq.push(temp / 2);``    ``}``    ``cout<

## Java

 `import` `java.util.Collections;``import` `java.util.PriorityQueue;` `class` `GFG {``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int` `arr[] = { ``1``, ``2``, ``3``, ``4``, ``5``, ``6``, ``7``, ``8``, ``9``, ``10` `};``        ``int` `K = ``9``;``        ``int` `N = arr.length;` `        ``// Max heap initialisation``        ``PriorityQueue pq = ``new` `PriorityQueue<>(``            ``N + K, Collections.reverseOrder());` `        ``// Add adjacent distances to max heap``        ``for` `(``int` `i = ``1``; i < N; i++) {``            ``pq.add((``float``)arr[i] - (``float``)arr[i - ``1``]);``        ``}` `        ``// For K times, half the maximum distance``        ``for` `(``int` `i = ``0``; i < K; i++) {``            ``float` `temp = pq.poll();``            ``pq.add(temp / ``2``);``            ``pq.add(temp / ``2``);``        ``}``        ``System.out.println(pq.peek());``    ``}``}``// This code is contributed by _govardhani`

## Python3

 `# Python3 program for the above approach` `# importing "bisect" for bisection operations``import` `bisect` `arr ``=` `[ ``1``, ``2``, ``3``, ``4``, ``5``, ``6``, ``7``, ``8``, ``9``, ``10` `]``K ``=` `9``N ``=` `len``(arr)` `# Max heap initialisation``pq ``=` `[]` `# Add adjacent distances to max heap``for` `i ``in` `range``(``1``, N):``    ``bisect.insort(pq,``float``(arr[i])``-``float``(arr[i``-``1``]))` `# For K times, half the maximum distance``for` `i ``in` `range``(K):``    ``temp``=``pq[``0``]``    ``pq.pop(``0``)``    ``pq.append(temp``/``2``)``    ``pq.append(temp``/``2``)` `print``(pq[``0``])` `# This code is contributed by Pushpesh Raj`

Time Complexity: O(NlogN)
Auxiliary Space: O(N+K)

My Personal Notes arrow_drop_up