Minimize operations to make all array elements | C # 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
using System ; using System . Collections . Generic ; public class GFG { class pair : IComparable < pair > { public int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } public int CompareTo ( pair p ) { return this . first - p . first ; } } static int minOperations ( int [ ] arr , int N , int K ) { List < pair > vp = new List < pair > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { vp . Add ( new pair ( arr [ i ] , i ) ) ; } vp . Sort ( ) ; int minCnt = 0 ; while ( vp . Count != 0 ) { int val , ind ; val = vp [ vp . Count - 1 ] . first ; ind = vp [ vp . Count - 1 ] . second ; minCnt ++ ; while ( vp . Count != 0 && vp [ vp . Count - 1 ] . first == val && ind - vp [ vp . Count - 1 ] . second + 1 <= K ) vp . RemoveAt ( vp . Count - 1 ) ; } return minCnt ; } public static void Main ( String [ ] args ) { int [ ] arr = { 18 , 11 , 18 , 11 , 18 } ; int K = 3 ; int N = arr . Length ; Console . Write ( minOperations ( arr , N , K ) ) ; } }