You need to reorder the array into some permutation B such that for every i:
∣Bi-Bi+1∣≤1
We must decide if such a permutation exists.
Key Insight
If we sort the array to get C (non-decreasing order):
In the sorted array, adjacent numbers are as close as possible.
Any other permutation can only make some adjacent differences bigger, never smaller.
So:
If the sorted array already has some adjacent pair with difference > 1,
then no permutation can satisfy the condition.If the sorted array has all adjacent differences ≤ 1, then the sorted array itself is a valid permutation.
Therefore, the check is simple:
Sort the array.
Check all adjacent pairs:
If for any i, C[i+1] - C[i] > 1 → print NO.
Otherwise → print YES.
Algorithm
For each test case:
Read N and array A.
Sort A.
For i from 0 to N-2:
If A[i+1] - A[i] > 1:
Print NO and stop checking this test.
If loop finishes without violation, print YES.
Time complexity per test: O(N log N) for sorting.
Given total N over tests ≤ 2 * 105, this is efficient.
Example
Sample 1:
A = [3, 2, 2, 3]
Sorted: [2, 2, 3, 3]
Differences: 0, 1, 0 → all ≤ 1 → YES.A = [1, 5]
Sorted: [1, 5]
Difference: 4 > 1 → NO.
Pseudocode:
Java code
C++ code
Python code
JavaScript code






Comments
Post a Comment