#C3202. Shortest Unsorted Subarray

    ID: 46604 Type: Default 1000ms 256MiB

Shortest Unsorted Subarray

Shortest Unsorted Subarray

Given an array of n integers, find the length of the shortest continuous subarray such that if you sort this subarray in non-decreasing order, the entire array becomes sorted in non-decreasing order.

Let the array be \(A = [a_1, a_2, \ldots, a_n]\). The task is to identify two indices \(i\) and \(j\) with \(1 \le i \le j \le n\) such that sorting the subarray \(A[i..j]\) makes the whole array sorted. Then, output \(j-i+1\). If the array is already sorted, output 0.

Input Format: The first line contains an integer \(n\) (the number of elements in the array). The second line contains \(n\) space-separated integers representing the array \(A\).

Output Format: Output a single integer which is the length of the shortest subarray that needs to be sorted.

inputFormat

The first line contains an integer \(n\) (\(1 \le n \le 10^5\)), which is the number of elements in the array. The second line contains \(n\) space-separated integers representing the elements of the array \(A\).

outputFormat

Output a single integer, the length of the shortest continuous subarray that, if sorted, results in the entire array being sorted in non-decreasing order. If the array is already sorted, output 0.

## sample
5
1 2 3 4 5
0

</p>