Minimum increments or decrements by D required to make all array elements equal | Function to find minimum count of operations required to make all array elements equal by incrementing or decrementing array elements by d ; Sort the array ; Traverse the array ; If difference between two consecutive elements are not divisible by D ; Store minimum count of operations required to make all array elements equal by incrementing or decrementing array elements by d ; Stores middle element of the array ; Traverse the array ; Update count ; Driver Code ; Given N & D ; Given array arr [ ] ; Function Call
def numOperation ( arr , N , D ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( ( arr [ i + 1 ] - arr [ i ] ) % D != 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT DEDENT count = 0 NEW_LINE mid = arr [ N // 2 ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT count += abs ( mid - arr [ i ] ) // D NEW_LINE DEDENT print ( count ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 NEW_LINE D = 2 NEW_LINE arr = [ 2 , 4 , 6 , 8 ] NEW_LINE numOperation ( arr , N , D ) NEW_LINE DEDENT