#C7789. Rearrange Array with Constrained Adjacent Differences
Rearrange Array with Constrained Adjacent Differences
Rearrange Array with Constrained Adjacent Differences
You are given an array of n integers and an integer k. Your task is to determine whether it is possible to rearrange the array such that the absolute difference between every two adjacent elements is at most k. Formally, if the rearranged array is a1, a2, ..., an, then for every index i (1 ≤ i < n), the condition
\( |a_{i+1} - a_i| \le k \)
must hold.
Note: A simple strategy is to sort the array in non-decreasing order. If in this sorted order, the difference between any pair of consecutive elements exceeds k, then no permutation can satisfy the requirement, and the answer will be NO
. Otherwise, output YES
.
It is guaranteed that the input array and the value of k will be such that the above approach is sufficient to determine the answer.
inputFormat
The input is read from standard input and has the following format:
T n1 k1 arr1[0] arr1[1] ... arr1[n1-1] n2 k2 arr2[0] arr2[1] ... arr2[n2-1] ...
Where:
- T is the number of test cases.
- For each test case, the first line contains two integers n and k.
- The second line of each test case contains n space-separated integers representing the array.
outputFormat
For each test case, print a single line to the standard output containing YES
if it is possible to rearrange the array under the given condition, or NO
otherwise.
4
3 2
1 3 5
4 4
-1 -5 3 2
2 0
100 100
5 1
1 2 8 4 10
YES
YES
YES
NO
</p>