Minimize subtraction followed by increments of adjacent elements required to make all array elements equal | Java program for the above approach ; 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
import java . io . * ; import java . util . * ; class GFG { static int findMinMoves ( int [ ] arr , int N ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) sum += arr [ i ] ; if ( sum % N != 0 ) return - 1 ; int avg = sum / N ; int total = 0 ; int needCount = 0 ; for ( int i = 0 ; i < N ; i ++ ) { needCount += ( arr [ i ] - avg ) ; total = Math . max ( Math . max ( Math . abs ( needCount ) , arr [ i ] - avg ) , total ) ; } return total ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 0 , 5 } ; int N = arr . length ; System . out . println ( findMinMoves ( arr , N ) ) ; } }