Open In App

Maximum of minimum difference of all pairs from subsequences of given size

Last Updated : 12 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer array arr[], the task is to find a subsequence of size k such that the minimum difference between any two of them is maximum. Return this largest minimum difference.

Examples:

Input: arr[] = [1, 2, 3, 5], k = 3
Output: 2
Explanation: Possible subsequences of size 3 are [1, 2, 3], [1, 2, 5], [1, 3, 5], and [2, 3, 5].
For [1, 3, 5], possible differences are (|1 - 3| = 2), (|3 - 5| = 2), and (|1 - 5| = 4), Minimum(2, 2, 4) = 2
For the remaining subsequences, the minimum difference comes out to be 1.
Hence, the maximum of all minimum differences is 2.

Input: arr[] = [5, 17, 11], k = 2
Output: 12
Explanation: Possible subsequences of size 2 are [5, 17], [17, 11], and [5, 11].
For [5, 17], possible difference is (|5 - 17| = 12), Minimum = 12
For [17, 11], possible difference is (|17 - 11| = 6), Minimum = 6
For [5, 11], possible difference is (|5 - 11| = 6), Minimum = 6
Maximum(12, 6, 6) = 12
Hence, the maximum of all minimum differences is 12.

[Naive Approach] Generate all Subsequences - O(2^n * k^2) Time and O(k) Space

The idea is to generate all possible subsequences of size k from arr[] and compute the minimum absolute difference between any two elements in each subsequence. We then take the maximum of these minimum differences across all subsequences. This brute-force approach ensures we check all possible selections but is inefficient for large inputs due to exponential growth in subsequences.

Time Complexity: O(2^n * k^2), as we generate all subsequences of size k and compute pairwise differences
Space Complexity: O(k), for storing each subsequence during computation.

[Expected Approach] Using Binary Search - O(nlogn) Time and O(1) Space

The idea is to first sort the array then use binary search. The key observation is that the largest possible minimum difference is between the farthest elements in a sorted array, while the smallest is between consecutive elements. Instead of brute force, we use binary search to efficiently determine the best minimum difference by checking if a valid subsequence can be formed for a given difference. This balances selecting distant elements while ensuring enough selections for the subsequence.

Steps to implement the above idea:

  • Sort the array to ensure elements are in increasing order.
  • Determine the search space as the smallest difference between consecutive elements and the difference between the first and last elements.
  • Use binary search on the minimum difference, setting start and end accordingly.
  • Check feasibility of a subsequence using helper function, ensuring k elements can be selected with at least mid difference.
  • Update search space if valid, try increasing mid; otherwise, decrease it.
  • Return the maximum possible minimum difference after the binary search completes.

Below is the implementation of the above approach:

C++
// C++ Code to find the maximum of all  
// minimum differences of pairs in a 
// subsequence using Binary Search
#include <bits/stdc++.h>  
using namespace std;  

// Function to check if a subsequence can  
// be formed with min difference mid  
bool canPlace(vector<int>& arr, int k, int mid) { 
    
    int count = 1; 
    int lastPosition = arr[0]; 
    int n = arr.size();

    // Iterate through the array to form a 
    // valid subsequence  
    for (int i = 1; i < n; i++) {  
        
        // Check if the difference meets 
        // the required minimum  
        if (arr[i] - lastPosition >= mid) {  
            lastPosition = arr[i];  
            count++; 
            
            // If we have selected k elements, 
            // return true  
            if (count == k) {  
                return true;  
            }  
        }  
    }  
    return false;  
}  

// Function to find the maximum of all  
// minimum differences of pairs in a subsequence  
int findMinDifference(vector<int>& arr, int k) { 
 
    int n = arr.size();
    sort(arr.begin(), arr.end());  

    // Start with the smallest difference
    // between consecutive elements  
    int start = INT_MAX;  
    for (int i = 1; i < n; i++) {  
        start = min(start, arr[i] - arr[i - 1]);  
    }  

    // End with the difference between the
    // first and last elements  
    int end = arr[n - 1] - arr[0];  
    int answer = 0;  

    // Perform binary search on the possible 
    // minimum difference values  
    while (start <= end) {  
        int mid = (start + end) / 2;  

        // If a valid subsequence can be formed
        // with min difference mid  
        if (canPlace(arr, k, mid)) {  
            answer = mid; 
            
            // Try for a larger minimum difference
            start = mid + 1;   
        } 
        else { 
            
            // Reduce the difference 
            end = mid - 1;  
        }  
    }  

    return answer;  
}  

// Driver Code  
int main() {  
    vector<int> arr = {1, 2, 3, 5};  
    int k = 3;  

    cout << findMinDifference(arr, k);  

    return 0;  
}  
Java
// Java Code to find the maximum of all  
// minimum differences of pairs in a 
// subsequence using Binary Search
import java.util.Arrays;  

class GfG {  

    // Function to check if a subsequence can  
    // be formed with min difference mid  
    static boolean canPlace(int[] arr, int k, int mid) {  
        
        int count = 1;  
        int lastPosition = arr[0];  
        int n = arr.length;  

        // Iterate through the array to form a  
        // valid subsequence  
        for (int i = 1; i < n; i++) {  
            
            // Check if the difference meets  
            // the required minimum  
            if (arr[i] - lastPosition >= mid) {  
                lastPosition = arr[i];  
                count++;  
                
                // If we have selected k elements,  
                // return true  
                if (count == k) {  
                    return true;  
                }  
            }  
        }  
        return false;  
    }  

    // Function to find the maximum of all  
    // minimum differences of pairs in a subsequence  
    static int findMinDifference(int[] arr, int k) {  

        int n = arr.length;  
        Arrays.sort(arr);  

        // Start with the smallest difference  
        // between consecutive elements  
        int start = Integer.MAX_VALUE;  
        for (int i = 1; i < n; i++) {  
            start = Math.min(start, arr[i] - arr[i - 1]);  
        }  

        // End with the difference between the  
        // first and last elements  
        int end = arr[n - 1] - arr[0];  
        int answer = 0;  

        // Perform binary search on the possible  
        // minimum difference values  
        while (start <= end) {  
            int mid = (start + end) / 2;  

            // If a valid subsequence can be formed  
            // with min difference mid  
            if (canPlace(arr, k, mid)) {  
                answer = mid;  
                
                // Try for a larger minimum difference  
                start = mid + 1;  
            }  
            else {  
                
                // Reduce the difference  
                end = mid - 1;  
            }  
        }  

        return answer;  
    }  

    // Driver Code  
    public static void main(String[] args) {  
        int[] arr = {1, 2, 3, 5};  
        int k = 3;  

        System.out.println(findMinDifference(arr, k));  
    }  
}  
Python
# Python Code to find the maximum of all  
# minimum differences of pairs in a 
# subsequence using Binary Search

# Function to check if a subsequence can  
# be formed with min difference mid  
def canPlace(arr, k, mid):  
    
    count = 1  
    lastPosition = arr[0]  
    n = len(arr)  

    # Iterate through the array to form a  
    # valid subsequence  
    for i in range(1, n):  

        # Check if the difference meets  
        # the required minimum  
        if arr[i] - lastPosition >= mid:  
            lastPosition = arr[i]  
            count += 1  

            # If we have selected k elements,  
            # return True  
            if count == k:  
                return True  

    return False  

# Function to find the maximum of all  
# minimum differences of pairs in a subsequence  
def findMinDifference(arr, k):  

    n = len(arr)  
    arr.sort()  

    # Start with the smallest difference  
    # between consecutive elements  
    start = float('inf')  
    for i in range(1, n):  
        start = min(start, arr[i] - arr[i - 1])  

    # End with the difference between the  
    # first and last elements  
    end = arr[n - 1] - arr[0]  
    answer = 0  

    # Perform binary search on the possible  
    # minimum difference values  
    while start <= end:  
        mid = (start + end) // 2  

        # If a valid subsequence can be formed  
        # with min difference mid  
        if canPlace(arr, k, mid):  
            answer = mid  

            # Try for a larger minimum difference  
            start = mid + 1  
        else:  

            # Reduce the difference  
            end = mid - 1  

    return answer  

# Driver Code  
if __name__ == "__main__":  
    arr = [1, 2, 3, 5]  
    k = 3  

    print(findMinDifference(arr, k))  
C#
// C# Code to find the maximum of all  
// minimum differences of pairs in a 
// subsequence using Binary Search
using System;

class GfG {  

    // Function to check if a subsequence can  
    // be formed with min difference mid  
    static bool canPlace(int[] arr, int k, int mid) {  
        
        int count = 1;  
        int lastPosition = arr[0];  
        int n = arr.Length;  

        // Iterate through the array to form a  
        // valid subsequence  
        for (int i = 1; i < n; i++) {  
            
            // Check if the difference meets  
            // the required minimum  
            if (arr[i] - lastPosition >= mid) {  
                lastPosition = arr[i];  
                count++;  
                
                // If we have selected k elements,  
                // return true  
                if (count == k) {  
                    return true;  
                }  
            }  
        }  
        return false;  
    }  

    // Function to find the maximum of all  
    // minimum differences of pairs in a subsequence  
    static int findMinDifference(int[] arr, int k) {  

        int n = arr.Length;  
        Array.Sort(arr);  

        // Start with the smallest difference  
        // between consecutive elements  
        int start = int.MaxValue;  
        for (int i = 1; i < n; i++) {  
            start = Math.Min(start, arr[i] - arr[i - 1]);  
        }  

        // End with the difference between the  
        // first and last elements  
        int end = arr[n - 1] - arr[0];  
        int answer = 0;  

        // Perform binary search on the possible  
        // minimum difference values  
        while (start <= end) {  
            int mid = (start + end) / 2;  

            // If a valid subsequence can be formed  
            // with min difference mid  
            if (canPlace(arr, k, mid)) {  
                answer = mid;  
                
                // Try for a larger minimum difference  
                start = mid + 1;  
            }  
            else {  
                
                // Reduce the difference  
                end = mid - 1;  
            }  
        }  

        return answer;  
    }  

    // Driver Code  
    public static void Main(string[] args) {  
        int[] arr = {1, 2, 3, 5};  
        int k = 3;  

        Console.WriteLine(findMinDifference(arr, k));  
    }  
}  
JavaScript
// JavaScript Code to find the maximum of all  
// minimum differences of pairs in a  
// subsequence using Binary Search  

// Function to check if a subsequence can  
// be formed with min difference mid  
function canPlace(arr, k, mid) {  
    let count = 1;  
    let lastPosition = arr[0];  
    let n = arr.length;  

    // Iterate through the array to form a  
    // valid subsequence  
    for (let i = 1; i < n; i++) {  

        // Check if the difference meets  
        // the required minimum  
        if (arr[i] - lastPosition >= mid) {  
            lastPosition = arr[i];  
            count++;  

            // If we have selected k elements,  
            // return true  
            if (count === k) {  
                return true;  
            }  
        }  
    }  

    return false;  
}  

// Function to find the maximum of all  
// minimum differences of pairs in a subsequence  
function findMinDifference(arr, k) {  
    let n = arr.length;  
    arr.sort((a, b) => a - b);  

    // Start with the smallest difference  
    // between consecutive elements  
    let start = Infinity;  
    for (let i = 1; i < n; i++) {  
        start = Math.min(start, arr[i] - arr[i - 1]);  
    }  

    // End with the difference between the  
    // first and last elements  
    let end = arr[n - 1] - arr[0];  
    let answer = 0;  

    // Perform binary search on the possible  
    // minimum difference values  
    while (start <= end) {  
        let mid = Math.floor((start + end) / 2);  

        // If a valid subsequence can be formed  
        // with min difference mid  
        if (canPlace(arr, k, mid)) {  
            answer = mid;  

            // Try for a larger minimum difference  
            start = mid + 1;  
        } else {  

            // Reduce the difference  
            end = mid - 1;  
        }  
    }  

    return answer;  
}  

// Driver Code  
let arr = [1, 2, 3, 5];  
let k = 3;  

console.log(findMinDifference(arr, k));  

Output
2

Time Complexity: O(n log n) due to sorting and binary search.
Space Complexity: O(1) as only a few variables are used.


Next Article

Similar Reads