Minimize operations to make all array elements | Java program for the above approach ; Function to find minimum the number of operations required to make all the array elements to - 1 ; Stores the array elements with their corresponding indices ; Push the array element and it 's index ; Sort the elements according to it 's first value ; Stores the minimum number of operations required ; Traverse until vp is not empty ; Stores the first value of vp ; Stores the second value of vp ; Update the minCnt ; Pop the back element from the vp until the first value is same as val and difference between indices is less than K ; Return the minCnt ; Driver Code
import java . util . * ; class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static int minOperations ( int arr [ ] , int N , int K ) { Vector < pair > vp = new Vector < pair > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { vp . add ( new pair ( arr [ i ] , i ) ) ; } Collections . sort ( vp , ( a , b ) -> a . first - b . first ) ; int minCnt = 0 ; while ( ! vp . isEmpty ( ) ) { int val , ind ; val = vp . get ( vp . size ( ) - 1 ) . first ; ind = vp . get ( vp . size ( ) - 1 ) . second ; minCnt ++ ; while ( ! vp . isEmpty ( ) && vp . get ( vp . size ( ) - 1 ) . first == val && ind - vp . get ( vp . size ( ) - 1 ) . second + 1 <= K ) vp . remove ( vp . size ( ) - 1 ) ; } return minCnt ; } public static void main ( String [ ] args ) { int arr [ ] = { 18 , 11 , 18 , 11 , 18 } ; int K = 3 ; int N = arr . length ; System . out . print ( minOperations ( arr , N , K ) ) ; } }