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 ; Given N & D ; Given array arr [ ] ; Function Call
function numOperation ( arr , N , D ) { arr . sort ( ) ; for ( let i = 0 ; i < N - 1 ; i ++ ) { if ( ( arr [ i + 1 ] - arr [ i ] ) % D != 0 ) { document . write ( " " ) ; return ; } } let count = 0 ; let mid = arr [ N / 2 ] ; for ( let i = 0 ; i < N ; i ++ ) { count += Math . abs ( mid - arr [ i ] ) / D ; } document . write ( count ) ; } let N = 4 , D = 2 ; let arr = [ 2 , 4 , 6 , 8 ] ; numOperation ( arr , N , D ) ;