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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( int arr [ ] , int N , int K ) { vector < pair < int , int > > vp ; for ( int i = 0 ; i < N ; i ++ ) { vp . push_back ( { arr [ i ] , i } ) ; } sort ( vp . begin ( ) , vp . end ( ) ) ; int minCnt = 0 ; while ( ! vp . empty ( ) ) { int val , ind ; val = vp . back ( ) . first ; ind = vp . back ( ) . second ; minCnt ++ ; while ( ! vp . empty ( ) && vp . back ( ) . first == val && ind - vp . back ( ) . second + 1 <= K ) vp . pop_back ( ) ; } return minCnt ; } int main ( ) { int arr [ ] = { 18 , 11 , 18 , 11 , 18 } ; int K = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minOperations ( arr , N , K ) ; return 0 ; }