Minimize subtraction followed by increments of adjacent elements required to make all array elements equal | Function to find the minimum number of moves required to make all array elements equal ; Store the total sum of the array ; Calculate total sum of the array ; If the sum is not divisible by N , then print " - 1" ; Stores the average ; Stores the count of operations ; Traverse the array arr [ ] ; Update number of moves required to make current element equal to avg ; Update the overall count ; Return the minimum operations required ; Driver Code
function findMinMoves ( arr , N ) { let sum = 0 ; for ( let i = 0 ; i < N ; i ++ ) sum += arr [ i ] ; if ( sum % N != 0 ) return - 1 ; let avg = sum / N ; let total = 0 ; let needCount = 0 ; for ( let i = 0 ; i < N ; i ++ ) { needCount += ( arr [ i ] - avg ) ; total = Math . max ( Math . max ( Math . abs ( needCount ) , arr [ i ] - avg ) , total ) ; } return total ; } let arr = [ 1 , 0 , 5 ] ; let N = arr . length ; document . write ( findMinMoves ( arr , N ) )