#K73667. Can Be Sorted with One Swap
Can Be Sorted with One Swap
Can Be Sorted with One Swap
Given an array of integers \(A = [a_1, a_2, \dots, a_n]\), determine whether it is possible to sort the array in non-decreasing order by performing at most one swap of two elements. In other words, if the array is not already sorted, you are allowed to swap exactly two elements once to try to make the array sorted. Formally, after swapping two distinct indices \(i\) and \(j\) (with \(i < j\)), the resulting array should satisfy \(a_1 \le a_2 \le \dots \le a_n\).
If the array is already sorted, the answer is YES
. Otherwise, if exactly one swap can correctly sort the array, output YES
; if not, output NO
.
inputFormat
The first line of input contains a single integer n (1 ≤ n ≤ 105), representing the number of elements in the array. The second line contains n space-separated integers, representing the array elements.
outputFormat
Output a single line with the string YES
if the array can be sorted in non-decreasing order by performing at most one swap, otherwise output NO
.## sample
4
1 2 3 4
YES