
Consider an array of size six. The elements of the array are { 6, 4, 3, 5, 5, 1 }, and the value of ‘K’ is 3.
If we select {1, 3, 6}, the output will be the difference of the maximum of (1, 3, 6) and the minimum of (1,3, 6), i.e. 5.
If we select {4, 5, 5}, the output will be the difference of the maximum of (4, 5, 5) and the minimum of (4, 5, 5), i.e. 1.
Among all such possible values, 1 is the minimum, and hence, it is the correct output.
The first line of input contains an integer T, denoting the number of test cases.
The first line of every test case contains two integers ‘N’ and ‘K’ denoting the size of the array/list and the number of elements in the subset, respectively.
The second line of every test case contains ‘N’ space-separated integers.
For every test case, return the minimum possible difference between the maximum and the minimum value in the subset of size ‘K’.
The output of each test case is printed in a separate line.
You don’t have to print anything; it has already been taken care of. Just implement the function.
1 <= T <= 5
1 <= K <= 100
K <= N <= 100
-10^5 <= ARR[i] <= 10^5
Time Limit: 1 sec
Recursively generate all the subsets of size ‘K’ and keep track of the minimum possible value of the difference between the maximum and the minimum value in each subset.
Initialize a variable ‘ANS’ by +ve infinity (i.e. INT_MAX), to store the final answer.
Subsets can be generated in the following way. For every element of the array, there are two options:
In any step, if the value of ‘K’ becomes 0, then we have found a subset of size ‘K’. Now traverse the current subset and find the minimum and the maximum value.
Update the ‘ANS’ if the difference between the maximum and the minimum value in the current subset is less than the ‘ANS’.
In the end, ‘ANS’ will contain the minimum difference between the maximum and the minimum value in any subset of length ‘K’. So return the ‘ANS’.
How can we minimise the difference between the maximum and the minimum value of any ‘K’ sized subset?
The idea is to sort the given array/list and choose each subset of ‘K’ continuous integers. We can sort the given array/list because while manipulating subset and finding the maximum and minimum value does not depend on the order of elements.
Steps are as follows :