VOOZH about

URL: https://www.geeksforgeeks.org/dsa/k-numbers-difference-maximum-minimum-k-number-minimized/

⇱ Choose m elements having minimum difference between max and min - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Choose m elements having minimum difference between max and min

Last Updated : 23 Jul, 2025

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

[Naive Approach] By Generating All Subsets

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.

[Expected Approach] Using Sliding Window

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 m is minimized.

First sort the array arr[] and then use two pointers to maintain a window of size m to find the subarray with the minimum difference between its last and first elements.



Output
2

Time Complexity: n*log(n), where n is the size of arr[].
Auxiliary Space: O(1)

Comment
Article Tags: