Minimum elements to be removed from the ends to make the array sorted | C ++ implementation of the approach ; Function to return the minimum number of elements to be removed from the ends of the array to make it sorted ; To store the final answer ; Two pointer loop ; While the array is increasing increment j ; Updating the ans ; Updating the left pointer ; Returning the final answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMin ( int * arr , int n ) { int ans = 1 ; for ( int i = 0 ; i < n ; i ++ ) { int j = i + 1 ; while ( j < n and arr [ j ] > = arr [ j - 1 ] ) j ++ ; ans = max ( ans , j - i ) ; i = j - 1 ; } return n - ans ; } int main ( ) { int arr [ ] = { 3 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << findMin ( arr , n ) ; return 0 ; }