text: Count minimum number of moves to front or end to sort an array | Java algorithm for above approach ; Pair class which will store element of array with its index ; Driver code ; Function to find minimum number of operation required so that array becomes meaningful ; Initializing array of Pair type which can be used to sort arr with respect to its values ; Sorting array num on the basis of value ; Initializing variables used to find maximum length of increasing streak in index ; Updating streak ; Returning number of elements left except streak
code: import java . util . * ; class GFG { public static class Pair { int val ; int idx ; Pair ( int val , int idx ) { this . val = val ; this . idx = idx ; } } public static void main ( String [ ] args ) { int n = 5 ; int [ ] arr = { 4 , 7 , 2 , 3 , 9 } ; System . out . println ( minOperations ( arr , n ) ) ; } public static int minOperations ( int [ ] arr , int n ) { Pair [ ] num = new Pair [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { num [ i ] = new Pair ( arr [ i ] , i ) ; } Arrays . sort ( num , ( Pair a , Pair b ) -> a . val - b . val ) ; int res = 1 ; int streak = 1 ; int prev = num [ 0 ] . idx ; for ( int i = 1 ; i < n ; i ++ ) { if ( prev < num [ i ] . idx ) { res ++ ; streak = Math . max ( res , streak ) ; } else res = 1 ; prev = num [ i ] . idx ; } return n - streak ; } }