#K42057. Minimized Difference Arrays

    ID: 27002 Type: Default 1000ms 256MiB

Minimized Difference Arrays

Minimized Difference Arrays

You are given an array of n positive integers and an integer k. The task is to rearrange the array so that the difference between the maximum and minimum values in some contiguous subarray of length k is minimized. Formally, if we denote a contiguous subarray of length k as \(a_i, a_{i+1}, \ldots, a_{i+k-1}\), we want to minimize \(\Delta = a_{i+k-1} - a_i\) over all valid \(i\). In case there are multiple subarrays achieving the same minimum difference, output the lexicographically smallest array overall.

The approach is to sort the array in non-decreasing order. Then, by considering every subarray of consecutive elements (of length \(k\)) in the sorted order, you can obtain the minimum difference \(\Delta = a_{i+k-1} - a_i\). Once the best window is found, the final result is constructed by placing the chosen subarray first (in the order it appears in the sorted array) and then appending the remaining elements in sorted order.

inputFormat

The input is given via stdin and has the following format:

T
n1 k1
a1 a2 ... an1
n2 k2
a1 a2 ... an2
... 

Here, T represents the number of test cases. For each test case, the first line contains two space‐separated integers n and k, where n is the number of elements in the array and k is the length of the subarray. The second line contains n positive integers representing the array elements.

outputFormat

For each test case, print the result to stdout in the following format:

minimized_difference
rearranged_array

The first line is the minimized difference (an integer), and the second line contains the rearranged array (the elements separated by spaces).

## sample
1
5 2
1 5 3 9 2
1

1 2 3 5 9

</p>