#K55532. Rearrange to Form a Consecutive Sequence
Rearrange to Form a Consecutive Sequence
Rearrange to Form a Consecutive Sequence
Given an array of integers, determine if it is possible to rearrange the array so that the resulting sequence satisfies the following condition: For every pair of adjacent elements, the difference is either 0 or exactly 1. In other words, if the unique elements (when sorted) are denoted by \(u_1, u_2, \ldots, u_k\), then for every \(i\) from 2 to \(k\) the condition
[ u_i - u_{i-1} \leq 1 ]
must hold true. If this condition holds, output YES
, otherwise output NO
.
Example:
- For the array
[1, 2, 2, 3, 4]
, the unique sorted array is[1, 2, 3, 4]
with consecutive differences of 1, so the answer isYES
. - For the array
[1, 3, 3, 4, 5, 7]
, the unique sorted array is[1, 3, 4, 5, 7]
and there is at least one gap greater than 1 (between 1 and 3, and 5 and 7), so the answer isNO
.
inputFormat
The input is given via standard input (stdin). The first line contains an integer (n) (the number of elements in the array). The next line contains (n) space-separated integers representing the elements of the array.
outputFormat
Print a single line to standard output (stdout) with the string YES
if the array can be rearranged to form a sequence where for every adjacent pair ( (a, b) ), the condition (b - a \in {0, 1}) holds. Otherwise, print NO
.## sample
5
1 2 2 3 4
YES