#K61017. Find Minimum Unsorted Subarray

    ID: 31216 Type: Default 1000ms 256MiB

Find Minimum Unsorted Subarray

Find Minimum Unsorted Subarray

You are given an array of integers. Your task is to determine the minimum length of a continuous subarray such that, if you sort this subarray in non-decreasing order, the entire array becomes sorted in non-decreasing order.

If the array is already sorted, your program should output 0.

The underlying idea is to identify the leftmost and rightmost indices where the array deviates from the sorted order. More formally, if the unsorted subarray spans indices \( l \) and \( r \), then sorting the subarray \( A[l\dots r] \) makes the whole array sorted. Compute and output \( r - l + 1 \) if the array is unsorted, or 0 if the array is already sorted.

Input and Output via Standard IO: Your solution should read from standard input and write to standard output.

inputFormat

The first line contains an integer n representing the number of elements in the array. The second line contains n space-separated integers representing the elements of the array.

For example:

7
2 6 4 8 10 9 15

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
7
2 6 4 8 10 9 15
5

</p>