Length of smallest subarray to be removed such that the remaining array is sorted | C ++ program for the above approach ; Find the length of the shortest subarray ; To store the result ; Calculate the possible length of the sorted subarray from left ; Array is sorted ; Calculate the possible length of the sorted subarray from left ; Update the result ; Calculate the possible length in the middle we can delete and update the result ; Update the result ; Return the result ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findLengthOfShortestSubarray ( int arr [ ] , int N ) { int minlength = INT_MAX ; int left = 0 ; int right = N - 1 ; while ( left < right && arr [ left + 1 ] >= arr [ left ] ) { left ++ ; } if ( left == N - 1 ) return 0 ; while ( right > left && arr [ right - 1 ] <= arr [ right ] ) { right -- ; } minlength = min ( N - left - 1 , right ) ; int j = right ; for ( int i = 0 ; i < left + 1 ; i ++ ) { if ( arr [ i ] <= arr [ j ] ) { minlength = min ( minlength , j - i - 1 ) ; } else if ( j < N - 1 ) { j ++ ; } else { break ; } } return minlength ; } int main ( ) { int arr [ ] = { 6 , 3 , 10 , 11 , 15 , 20 , 13 , 3 , 18 , 12 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ( findLengthOfShortestSubarray ( arr , N ) ) ; }