#K66872. Minimize Maximum Difference
Minimize Maximum Difference
Minimize Maximum Difference
You are given an array of n integers. Your task is to rearrange the array in a manner that minimizes the maximum difference between any two consecutive elements. It turns out that sorting the array in non-decreasing order always provides such an arrangement.
The problem is formally defined as follows: Given an array \(A = [a_1, a_2, \dots, a_n]\), find a permutation \(B\) of \(A\) such that the quantity \(\max_{1 \leq i < n} |B_{i+1} - B_i|\) is minimized. The optimal solution, as you might expect, is to simply sort the array.
Examples:
- For
n = 4
andarr = [1, 3, 2, 6]
, the output is1 2 3 6
. - For
n = 5
andarr = [10, 1, 3, 2, 5]
, the output is1 2 3 5 10
. - For
n = 7
andarr = [-1, -3, 5, 4, 2, 0, -2]
, the output is-3 -2 -1 0 2 4 5
.
Note: The array may contain negative numbers and duplicate values. The input and output should be handled via standard input (stdin) and standard output (stdout), respectively.
inputFormat
The input is given in two lines:
- The first line contains a single integer \(n\) representing the number of elements in the array.
- The second line contains \(n\) space-separated integers representing the array elements.
outputFormat
Output the rearranged array as \(n\) space-separated integers on a single line. The arrangement should minimize the maximum difference between any two adjacent elements (i.e., it should be sorted in non-decreasing order).
## sample4
1 3 2 6
1 2 3 6
</p>