Minimize moves required to make array elements equal by incrementing and decrementing pairs | Set 2 | Function to find the minimum number of increment and decrement of pairs required to make all array elements equal ; Stores the sum of the array ; If sum is not divisible by N ; Update sum ; Store the minimum number of operations ; Iterate while i is less than N ; Add absolute difference of current element with k to ans ; Increase i bye 1 ; Return the value in ans2 ; Given Input ; Function Call
function find ( arr , N ) { let Sum = 0 ; let i = 0 ; let ans = 0 ; for ( i = 0 ; i < N ; i ++ ) { Sum += arr [ i ] ; } if ( Sum % N ) { return - 1 ; } else { k = Math . floor ( Sum / N ) ; ans = 0 ; i = 0 ; while ( i < N ) { ans = ans + Math . abs ( k - arr [ i ] ) ; i += 1 ; } } return Math . floor ( ans / 2 ) ; } let arr = [ 5 , 4 , 1 , 10 ] let N = arr . length ; document . write ( find ( arr , N ) ) ;