


Let there be 6 children and 3 gifts. If the position of the children is [3, 6, 7, 10, 17, 25], the minimum distance Santa has to walk is 4m which can be achieved in many ways, one of them being Santa landing at the 1st child and walking till the 3rd child (distance = (6m - 3m) + (7m - 6m) = 4m).
The first line of input contains an integer ‘T’ denoting the number of test cases to run. Then the test case follows.
The first line of each test case contains two space-separated integers, ‘N’ and ‘K’ denoting the number of children and number of gifts respectively.
The next line contains ‘N’ space-separated integers denoting the array “distance”.
For each test case, return an integer denoting the minimum distance Santa has to travel.
Output for each test case will be printed in a new line.
You do not need to print anything; it has already been taken care of. Just implement the given functions.
1 <= T <= 100
1 <= N <= 10000
1 <= K <= 10000
1 <= distance[i] < 10^9
Time Limit: 1 sec
We can note that it is always optimal to distribute gifts to ‘K’ children who are adjacent to each other.
For example, if the position of children are [2, 4, 7] and K = 2, it is optimal to give gifts to children with positions 2 and 4. If the positions were to be [2, 5, 7], it is optimal to give gifts to children at positions 5 and 7. In general, if the positions are [p1, p2, p3] where p1 < p2 < p3 and K = 2, it is never optimal to distribute gifts to children at p1 and p3.
We can start by sorting the “distance” array, so that we get the positions of children in increasing order. Then we can calculate the minimum distance Santa has to travel in case he lands at the ith child for each ‘i’ where 1 <= i <= N - K + 1 and walks towards the right(or increasing distance from park’s gate).
Note that if Santa lands on a child with index greater than N - K + 1, the number of children to his right are less than K and so he cannot distribute all gifts.
We can do that by simply iterating through each ‘i’ from 1 to N - K + 1, and for each ‘i’ calculate distance[i + K - 1] - distance[i] (which means we distributed gifts to each child with index between [i, i + K - 1]). We then have to store the minimum of all the distances to get the overall minimum distance.
Algorithm: