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

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 = 1Output: 2Explanation: 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 = 9Output: 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++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <iostream>using namespace std; // Function to check if it is possible// to add K points such that the maximum// distance between adjacent points is Dbool 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 betweendouble 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 Codeint 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 program for the above approachimport 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 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 Ddef 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 betweendef 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 Codeif __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# program for the above approachusing 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
<script>       // JavaScript Program to implement       // the above approach        // Function to check if it is possible       // to add K points such that the maximum       // distance between adjacent points is D       function isPossible(D, arr,           N, K)       {                   // Stores the count of point used           let used = 0;            // Iterate over all given points           for (let i = 0; i < N - 1; ++i) {                // Add number of points required               // to be placed between ith               // and (i+1)th point               used += Math.floor((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       function minMaxDist(stations, N, K)       {                   // Stores the lower bound and upper           // bound of the given range           let low = 0, high = 1e8;            // Perform binary search           while (high - low > 1e-6) {                // Find the middle value               let mid = (low + high) / 2;                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.toFixed(1);       }        // Driver Code       let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];       let K = 9;       let N = arr.length;        document.write(minMaxDist(arr, N, K));     // This code is contributed by Potta Lokesh   </script>
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++
Java
Python3
#include<bits/stdc++.h>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<<pq.top()<<endl;    return 0;} // This code is contributed by shinjanpatra.
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<Float> 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 program for the above approach # importing "bisect" for bisection operationsimport bisect arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]K = 9N = len(arr) # Max heap initialisationpq = [] # Add adjacent distances to max heapfor i in range(1, N):    bisect.insort(pq,float(arr[i])-float(arr[i-1])) # For K times, half the maximum distancefor 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)
lokeshpotta20
ankthon
_saurabh_jaiswal
29AjayKumar
govardhani
rkbhola5
shinjanpatra
pushpeshrajdx01
Binary Search
Google
Arrays
Mathematical
Searching
Google
Arrays
Searching
Mathematical
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
What is Data Structure: Types, Classifications and Applications
Chocolate Distribution Problem
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Coin Change | DP-7