#K37337. Almost Sorted Array

    ID: 25954 Type: Default 1000ms 256MiB

Almost Sorted Array

Almost Sorted Array

You are given an array of integers. Your task is to determine whether the array can be sorted in non-decreasing order by swapping at most one pair of elements. In other words, you need to check if the given array is already sorted or can be made sorted by performing a single swap of two distinct elements.

Formally, let \(a_1, a_2, \dots, a_n\) be the array. Determine if there exist indices \(i\) and \(j\) with \(i < j\) such that if you swap \(a_i\) and \(a_j\), the resulting array is sorted in non-decreasing order. If the array is initially sorted, it is also considered valid.

inputFormat

The input is read from standard input (stdin) and consists of two lines:

  1. The first line contains a single integer \(n\), the number of elements in the array.
  2. The second line contains \(n\) space-separated integers representing the array elements.

outputFormat

Output a single line to standard output (stdout):

  • True if the array can be sorted by swapping at most one pair of elements.
  • False otherwise.
## sample
4
10 20 30 40
True