Minimum operations to make Array equal by repeatedly adding K from an element and subtracting K from other | Java Program for the above approach ; 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 ; Driver Code ; Given Input ; Function Call
import java . io . * ; class GFG { static void miniOperToMakeAllEleEqual ( int arr [ ] , int n , int k ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; } if ( sum % n != 0 ) { System . out . println ( - 1 ) ; return ; } int valueAfterDivision = sum / n ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( Math . abs ( valueAfterDivision - arr [ i ] ) % k != 0 ) { System . out . println ( - 1 ) ; return ; } count += Math . abs ( valueAfterDivision - arr [ i ] ) / k ; } System . out . println ( ( int ) count / 2 ) ; } public static void main ( String [ ] args ) { int n = 3 , k = 3 ; int arr [ ] = { 5 , 8 , 11 } ; miniOperToMakeAllEleEqual ( arr , n , k ) ; } }