Minimize operations to make all array elements | 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
function minOperations ( arr , N , K ) { let vp = [ ] ; for ( let i = 0 ; i < N ; i ++ ) { vp . push ( { " " : arr [ i ] , " " : i } ) ; } vp . sort ( function ( a , b ) { return a . first - b . first ; } ) ; let minCnt = 0 ; while ( vp . length > 0 ) { let val , ind ; val = vp [ vp . length - 1 ] . first ; ind = vp [ vp . length - 1 ] . second ; minCnt ++ ; while ( vp . length > 0 && ( vp [ vp . length - 1 ] . first == val ) && ( ind - vp [ vp . length - 1 ] . second + 1 <= K ) ) { vp . pop ( ) ; } } return minCnt ; } let arr = [ 18 , 11 , 18 , 11 , 18 ] ; let K = 3 ; let N = arr . length ; document . write ( minOperations ( arr , N , K ) ) ;