Maximum of minimum difference of all pairs from subsequences of given size
Last Updated :
12 Mar, 2025
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));
Time Complexity: O(n log n) due to sorting and binary search.
Space Complexity: O(1) as only a few variables are used.
Similar Reads
Find sum of difference of maximum and minimum over all possible subsets of size K
Given an array arr[] of N integers and an integer K, the task is to find the sum of the difference between the maximum and minimum elements over all possible subsets of size K. Examples: Input: arr[] = {1, 1, 3, 4}, K = 2Output: 11Explanation:There are 6 subsets of the given array of size K(= 2). Th
12 min read
Subsequence with maximum pairwise absolute difference and minimum size
Given an array arr[] of N integers, the task is to print the subsequence from the given array with the maximum pairwise absolute difference of adjacent elements. If multiple such subsequences exist, then print the subsequence with the smallest length. Examples: Input: arr[] = {1, 2, 4, 3, 5} Output:
7 min read
Minimum possible sum of absolute difference of pairs from given arrays
Given two arrays a[] and b[] of size N and M respectively (N < M), the task is to find the minimum possible sum of absolute difference of pairs formed by pairing each element of array a[] with an element of array b[] Note: Each element of each array can be considered only once. Examples: Input: a
8 min read
Find the sum of maximum difference possible from all subset of a given array.
We are given an array arr[] of n non-negative integers (repeated elements allowed), find out the sum of maximum difference possible from all subsets of the given array. Suppose max(s) represents the maximum value in any subset 's' whereas min(s) represents the minimum value in the set 's'. We need t
7 min read
Minimum and Maximum sum of absolute differences of pairs
Given an array of N integers where N is even, find the minimum and maximum sum of absolute difference of N/2 pairs formed by pairing every element with one other element. Examples: Input: a[] = {10, -10, 20, -40} Output: min_sum = 40, max_sum = 80 Explanation: Pairs selected for minimum sum (-10, -4
8 min read
Maximise sum of product of pairs by choosing subsequence of same length from given Arrays
Given two integer arrays A[] and B[] of different length N and M respectively, the task is to choose any subsequence of same length from each array such that sum of product of pairs at corresponding indices in the subsequence is maximised. Example: Input: A = {4, -1, -3, 3}, B = {-4, 0, 5}Output: 27
15+ min read
Minimum difference between max and min of all K-size subsets
Given an array of integer values, we need to find the minimum difference between the maximum and minimum of all possible K-length subsets. Examples : Input : arr[] = [3, 5, 100, 101, 102] K = 3 Output : 2 Explanation : Possible subsets of K-length with their differences are, [3 5 100] max min diff i
7 min read
Minimum value of maximum absolute difference of all adjacent pairs in an Array
Given an array arr, containing non-negative integers and (-1)s, of size N, the task is to replace those (-1)s with a common non-negative integer such that the maximum absolute difference of all adjacent pairs is minimum. Print this minimum possible value of the maximum absolute difference. Examples:
9 min read
Length of longest subsequence having absolute difference of all pairs divisible by K
Given an array, arr[] of size N and an integer K, the task is to find the length of the longest subsequence from the given array such that the absolute difference of each pair in the subsequence is divisible by K. Examples: Input: arr[] = {10, 12, 16, 20, 32, 15}, K = 4 Output: 4 Explanation:The Lon
6 min read
Minimize difference between maximum and minimum element of all possible subarrays
Given an array arr[ ] of size N, the task is to find the minimum difference between maximum and minimum elements of all possible sized subarrays of arr[ ]. Examples: Input: arr[] = { 5, 14, 7, 10 } Output: 3Explanation: {7, 10} is the subarray having max element = 10 & min element = 7, and their
5 min read