#C471. Minimize Subarray Range
Minimize Subarray Range
Minimize Subarray Range
You are given an array of n integers and a number k which represents the size of a subarray. The task is to rearrange the array such that in every contiguous subarray of size k, the difference between the maximum and minimum elements is minimized. One effective approach to achieve this is to sort the array. When sorted, every subarray of size k automatically minimizes the range between its smallest and largest elements. If there are multiple solutions, any valid rearrangement will be accepted.
Note: The optimal solution involves sorting the array which guarantees that the difference \(\min_{i \leq j \leq i+k-1}(a[j])\) and \(\max_{i \leq j \leq i+k-1}(a[j])\) is minimized for every valid starting index \(i\).
inputFormat
The first line of input contains two integers n
and k
, where n
is the number of elements in the array and k
is the size of the subarray.
The second line contains n
space-separated integers representing the elements of the array.
outputFormat
Output the rearranged array as a sequence of n
space-separated integers on a single line.
7 3
10 1 2 7 5 8 9
1 2 5 7 8 9 10