#C2873. Sort Array by Reversing One Subarray
Sort Array by Reversing One Subarray
Sort Array by Reversing One Subarray
You are given an array of n integers. Your task is to determine whether it is possible to sort the entire array in non-decreasing order by performing exactly one operation: reversing a contiguous (i.e., consecutive) subarray. Formally, you can select two indices l and r (with \(1 \le l \le r \le n\)) and reverse the segment \(a_l, a_{l+1}, \dots, a_r\). If the array is already sorted in non-decreasing order, it is considered valid.
For example, consider the array \([4, 3, 2, 1, 5]\). By reversing the subarray from index 1 to 4 (1-indexed), you obtain \([1, 2, 3, 4, 5]\), which is sorted. However, for the array \([2, 1, 4, 3]\), no single reversal can result in a sorted array.
Your task is to decide if such a reversal exists. If it is possible, output YES
; otherwise, output NO
.
inputFormat
The first line of input contains a single integer T (the number of test cases). Each test case is described by two lines:
- The first line contains an integer n, the size of the array.
- The second line contains n space-separated integers representing the elements of the array.
All input is read from standard input (stdin).
outputFormat
For each test case, output a single line containing YES
if it is possible to sort the given array in non-decreasing order by reversing exactly one contiguous subarray, or NO
otherwise. All output should be written to standard output (stdout).
4
5
4 3 2 1 5
3
1 2 3
4
2 1 4 3
6
3 1 2 5 4 6
YES
YES
NO
NO
</p>