Minimum operations to make Array equal by repeatedly adding K from an element and subtracting K from other | Function to find the minimum number of operations to make all the elements of the array equal ; Store the sum of the array arr [ ] ; Traverse through the array ; If it is not possible to make all array element equal ; Store the minimum number of operations needed ; Traverse through the array ; Finally , print the minimum number operation to make array elements equal ; Given Input ; Function Call
function miniOperToMakeAllEleEqual ( arr , n , k ) { let sum = 0 ; for ( let i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; } if ( sum % n ) { document . write ( - 1 ) ; return ; } let valueAfterDivision = sum / n ; let count = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( Math . abs ( valueAfterDivision - arr [ i ] ) % k != 0 ) { document . write ( - 1 ) ; return ; } count += Math . abs ( valueAfterDivision - arr [ i ] ) / k ; } document . write ( Math . floor ( count / 2 ) ) ; } let n = 3 , k = 3 ; let arr = [ 5 , 8 , 11 ] ; miniOperToMakeAllEleEqual ( arr , n , k ) ;