Minimum elements to be removed from the ends to make the array sorted | 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
function findMin ( arr , n ) { let ans = 1 ; for ( let i = 0 ; i < n ; i ++ ) { let j = i + 1 ; while ( j < n && arr [ j ] >= arr [ j - 1 ] ) j ++ ; ans = Math . max ( ans , j - i ) ; i = j - 1 ; } return n - ans ; } let arr = [ 3 , 2 , 1 ] ; let n = arr . length ; document . write ( findMin ( arr , n ) ) ;