#C1709. Reverse Subarray Sorting

    ID: 44944 Type: Default 1000ms 256MiB

Reverse Subarray Sorting

Reverse Subarray Sorting

You are given an array of integers \(a = [a_1, a_2, \dots, a_n]\). Your task is to determine whether it is possible to sort the array in non-decreasing order by reversing at most one contiguous subarray. In other words, you may choose a segment \([l, r]\) and reverse it such that the resulting array is sorted in non-decreasing order (i.e. \(a_1 \le a_2 \le \dots \le a_n\)). Note that if the given array is already sorted, you should print YES.

Examples:

  • For the array [1, 5, 3, 3, 2], reversing the subarray from index 2 to index 5 produces [1, 2, 3, 3, 5] which is sorted. Therefore, the answer is YES.
  • For the array [4, 3, 2, 1], reversing the entire array gives [1, 2, 3, 4] which is sorted. Answer is YES.
  • For the array [1, 2, 3], no reversal is needed. Answer is YES.
  • For the array [2, 3, 8, 6, 5, 1, 10], no single reversal can sort the array. Answer is NO.

inputFormat

The input is read from stdin and has the following format:

T
N
a1 a2 ... aN
N
a1 a2 ... aN
... (T test cases in total)

Where:

  • T is the number of test cases.
  • For each test case, the first line contains an integer N (the number of elements in the array), followed by a line with N space-separated integers.

outputFormat

For each test case, output a single line to stdout containing either YES if the array can be sorted by reversing at most one subarray, or NO otherwise.

## sample
3
5
1 5 3 3 2
4
4 3 2 1
3
1 2 3
YES

YES YES

</p>