Minimize moves required to make array elements equal by incrementing and decrementing pairs | Set 2 | Java program for the above approach ; 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 ; Driver Code ; Given Input ; Function Call
import java . util . * ; class GFG { static int find ( ArrayList < Integer > arr , int N ) { int Sum = 0 ; for ( int item : arr ) Sum += item ; if ( Sum % N == 1 ) return - 1 ; int k = Sum / N ; int ans = 0 ; int i = 0 ; while ( i < N ) { ans = ans + Math . abs ( k - arr . get ( i ) ) ; i += 1 ; } return ans / 2 ; } public static void main ( String [ ] args ) { ArrayList < Integer > arr = new ArrayList < > ( ) ; arr . add ( 5 ) ; arr . add ( 4 ) ; arr . add ( 1 ) ; arr . add ( 10 ) ; int N = arr . size ( ) ; System . out . println ( find ( arr , N ) ) ; } }