#C3497. Rearrange Array with Bounded Differences
Rearrange Array with Bounded Differences
Rearrange Array with Bounded Differences
You are given an array of N integers and a number M. Your task is to rearrange the array so that the absolute difference between any two consecutive elements is at most M. Formally, if the rearranged array is A = [A1, A2, ..., AN], then it must hold that \(|A_{i+1} - A_i| \le M\) for all valid i (1 ≤ i < N). If no valid rearrangement exists, output -1.
A straightforward strategy is to sort the array. After sorting, check if the absolute difference between every pair of consecutive numbers is at most M. If the condition is violated at any point, the answer is -1. Otherwise, output the sorted array.
inputFormat
The input is read from standard input (stdin) and has the following format:
N M A1 A2 ... AN
where:
- N (1 ≤ N ≤ 105) is the number of elements in the array.
- M (0 ≤ M ≤ 109) is the maximum allowed absolute difference between any two consecutive numbers in the rearranged array.
- The second line contains N space-separated integers Ai.
outputFormat
The output should be written to standard output (stdout). If a valid rearrangement exists, print the rearranged array as N space-separated integers. If no valid rearrangement exists, print -1.
## sample5 3
1 2 8 4 5
1 2 4 5 8
</p>