Minimize adding odd and subtracting even numbers to make all array elements equal to K | Function to find the minimum operations required to make array elements equal to K ; Stores minimum count of operations ; Traverse the given array ; If K is greater than arr [ i ] ; If ( K - arr [ i ] ) is even ; Update cntOpe ; Update cntOpe ; If K is less than arr [ i ] ; If ( arr [ i ] - K ) is even ; Update cntOpe ; Update cntOpe ; Driver Code
def MinOperation ( arr , N , K ) : NEW_LINE INDENT cntOpe = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( K > arr [ i ] ) : NEW_LINE INDENT if ( ( K - arr [ i ] ) % 2 == 0 ) : NEW_LINE INDENT cntOpe += 2 NEW_LINE DEDENT else : NEW_LINE INDENT cntOpe += 1 NEW_LINE DEDENT DEDENT elif ( K < arr [ i ] ) : NEW_LINE INDENT if ( ( K - arr [ i ] ) % 2 == 0 ) : NEW_LINE INDENT cntOpe += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cntOpe += 2 NEW_LINE DEDENT DEDENT DEDENT return cntOpe NEW_LINE DEDENT arr = [ 8 , 7 , 2 , 1 , 3 ] NEW_LINE K = 5 NEW_LINE N = len ( arr ) NEW_LINE print ( MinOperation ( arr , N , K ) ) NEW_LINE