#C9767. Arrange Books with Limited Swap Difference
Arrange Books with Limited Swap Difference
Arrange Books with Limited Swap Difference
Alice has n books with various heights. She wants to arrange them in non-decreasing order using a series of swaps. However, in each swap, she can only swap two books if the absolute difference of their heights is at most \(k\). Determine whether it is possible to rearrange the books in non-decreasing order under this restriction.
Formally, let the books' heights be given by an array \(h[0 \ldots n-1]\). You are allowed to swap \(h[i]\) and \(h[j]\) if \(|h[i]-h[j]| \leq k\). If it is possible to achieve a non-decreasing sequence by applying a series of valid swaps, print YES
; otherwise, print NO
.
Note: The absolute difference condition is given by the inequality \(|h[i]-h[j]| \leq k\). This condition must hold for every swap made in the process.
inputFormat
The first line of input contains a single integer \(t\) (the number of test cases).
For each test case, the first line contains two integers \(n\) and \(k\) where \(n\) is the number of books and \(k\) is the maximum allowed height difference for a swap. The second line contains \(n\) integers representing the heights of the books.
\(\textbf{Input Format:}\)
\(t\)
\(n\) \(k\)
\(h_0\) \(h_1\) ... \(h_{n-1}\)
...
outputFormat
For each test case, print YES
if it is possible to arrange the books in non-decreasing order using the allowed swaps, or NO
otherwise.
\(\textbf{Output Format:}\)
For each test case, one line with the result YES
or NO
.
3
5 2
1 5 3 3 7
4 1
4 3 1 2
6 10
10 20 30 25 15 35
YES
NO
YES
</p>