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
def minOperations ( arr , N , K ) : NEW_LINE INDENT vp = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT vp . append ( [ arr [ i ] , i ] ) NEW_LINE DEDENT vp . sort ( ) NEW_LINE minCnt = 0 NEW_LINE while ( len ( vp ) != 0 ) : NEW_LINE INDENT val = vp [ - 1 ] [ 0 ] NEW_LINE ind = vp [ - 1 ] [ 1 ] NEW_LINE minCnt += 1 NEW_LINE while ( len ( vp ) != 0 and vp [ - 1 ] [ 0 ] == val and ind - vp [ - 1 ] [ 1 ] + 1 <= K ) : NEW_LINE INDENT vp . pop ( ) NEW_LINE DEDENT DEDENT return minCnt NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 18 , 11 , 18 , 11 , 18 ] NEW_LINE K = 3 NEW_LINE N = len ( arr ) NEW_LINE print ( minOperations ( arr , N , K ) ) NEW_LINE DEDENT