#K34387. Longest Subarray to Sort

    ID: 25298 Type: Default 1000ms 256MiB

Longest Subarray to Sort

Longest Subarray to Sort

Given an array of integers, your task is to determine the length of the longest contiguous subarray such that if that subarray is sorted in non-decreasing order, the entire array becomes sorted.

If the array is already sorted, output 0. In case there are multiple such subarrays, any one length that satisfies the condition is acceptable.

Mathematically, for an array \(X = [x_1, x_2, \ldots, x_n]\), find indices \(L\) and \(R\) such that sorting the subarray \(X[L \ldots R]\) results in the entire array being sorted. The answer is \(R - L + 1\).

inputFormat

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

outputFormat

Output a single integer: the length of the contiguous subarray that needs to be sorted so that the entire array becomes sorted.## sample

7
2 6 3 8 10 9 15
5