![]() |
VOOZH | about |
Given an array arr[] of n integers. The task is to pick exactly m elements such that the maximum difference between any pair of these m elements in minimum.
Examples:
Input: arr[] = {7, 3, 2, 4, 9, 12, 56}, m = 3
Output: 2
Explanation: We pick {3, 2, 4}, we will get the minimum difference, that is 2.Input: arr[] = {7, 3, 2, 4, 9, 12, 56}, m = 5
Output: 7
Explanation: We pick {3, 2, 4, 9, 7}, we will get the minimum difference, that is 9 - 2 = 7.Input : arr[] = {10, 100, 300, 200, 1000, 20, 30}
m = 3
Output : 20
We pick {10, 20, 30}.
max(10, 20, 30) - min(10, 20, 30) = 30 - 10 = 20.
The idea is to generate all subsets of size m of arr[]. For every subset, find the difference between the maximum and minimum elements in it. Finally, return the minimum difference.
The idea is to use sliding window technique and choose consecutive elements from a sorted array to minimize the difference. After sorting the array, the difference between the maximum and minimum values in any window of size
mis minimized.First sort the array
arr[]and then use two pointers to maintain a window of sizemto find the subarray with the minimum difference between its last and first elements.
2
Time Complexity: n*log(n), where n is the size of arr[].
Auxiliary Space: O(1)