
Input: A = [1,3,6], K = 3
Output: 3
Explanation: B = [4,6,3]
The first line of input contains a single integer ‘T’ denoting the number of test cases given.
The first line of each test case input contains two space-separated integers ‘N’ and ‘K’. Where ‘N’ denotes the number of elements in the array while ‘K’ is the value to be added or subtracted from each A[i] so that the so formed list (array) ‘B’ has the smallest possible difference between its maximum and minimum element.
The next line of input for each test case contains ‘N’ space-separated integers (elements of the list/array).
For every test case, print the smallest possible difference between the maximum value of B and the minimum value of B.
Print the output of each test case in a separate line.
You do not need to print anything; it has already been taken care of. Just implement the given function.
1 <= T <= 100
1 <= A.length <= 5000
0 <= A[i] <= 10000
0 <= K <= 10000
Time Limit: 1 sec
Using the intutuin that if A[i] < A[j], we don't need to consider when A[i] goes down while A[j] goes up. Since, the interval (A[i] + K, A[j] - K) would already always be a subset of (A[i] - K, A[j] + K) (here, (a, b) for a > b denotes (b, a) instead.)
That means that it is never worse to choose (up, down) instead of (down, up).
Now, for a sorted list (array) A, assume that element A[i] is the largest i that goes up. Then, A[0] + K, A[i] + K, A[i+1] - K, A[A.length - 1] - K are the only relevant values for calculating the answer: every other value is between one of these extremal values.
Algorithm