#K35927. Reorder Array with Adjacent Difference Condition
Reorder Array with Adjacent Difference Condition
Reorder Array with Adjacent Difference Condition
You are given an array of n positive integers. Your task is to determine whether it is possible to reorder the array such that the absolute difference between every pair of adjacent elements is strictly greater than 1. In other words, for a permutation \(a_1, a_2, \ldots, a_n\) of the original array, the condition
[ |a_i - a_{i+1}| > 1 \quad \text{for all } 1 \le i < n ]
must hold.
Examples:
- For
n = 5
and array[1, 3, 6, 9, 12]
, one valid ordering is the sorted order, where adjacent differences are \(2, 3, 3, 3\); hence, the answer isYES
. - For
n = 4
and array[1, 2, 3, 4]
, no reordering can avoid an adjacent difference of 1; hence, the answer isNO
.
Note: The intended solution in this problem uses a simple check on the sorted array. That is, after sorting, if there exists any pair of consecutive elements whose difference is less than or equal to 1, then output NO
; otherwise, output YES
.
inputFormat
The input is read from standard input (stdin
) and consists of 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 positive integers.
outputFormat
Output a single line to standard output (stdout
) containing either YES
if the array can be reordered to meet the condition, or NO
otherwise.
The answer must be exactly one of these two strings.
## sample5
1 3 6 9 12
YES