
Given ‘ARR’ : {1, 3, 2, 4, 5}
Selecting subarray {3, 2} and sorting it will make the whole array sorted.
Resultant ‘ARR’ : {1, 2, 3, 4, 5}
So, the minimum length will be 2.
The first line of input contains an integer ‘T’, the number of test cases.
The first line of each test case contains a single integer ‘N’ representing the size of the array.
The second line contains 'N' single space-separated integers representing the elements of the array.
For each test case, print a single integer representing the size of the subarray.
Print the output of each test case in a separate line.
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 2*10^3
1 <= ARR[i] <= 5*10^3
Time Limit : 1 sec
The basic idea is to create a copy of the given array and sort it. Then, by comparing the elements of both of the arrays, we can find the leftmost and rightmost mismatched elements.
Here is the algorithm :
The approach is to find the index of the leftmost element which is greater than its next element and similarly to find the index of the rightmost element which is smaller than its previous element. We also need to check whether the minimum element present in the subarray is not smaller than any element present in the prefix part (excluding the part of subarray) of the array. Similarly, we need to check for the suffix part also.
Here is the algorithm :