Minimum increments or decrements by D required to make all array elements equal | Java program for the above approach ; Function to find minimum count of operations required to make all array elements equal by incrementing or decrementing array elements by d ; Sort the array ; Traverse the array ; If difference between two consecutive elements are not divisible by D ; Store minimum count of operations required to make all array elements equal by incrementing or decrementing array elements by d ; Stores middle element of the array ; Traverse the array ; Update count ; Driver code ; Given N & D ; Given array arr [ ] ; Function Call
import java . util . * ; class GFG { static void numOperation ( int arr [ ] , int N , int D ) { Arrays . sort ( arr ) ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( ( arr [ i + 1 ] - arr [ i ] ) % D != 0 ) { System . out . println ( " - 1" ) ; return ; } } int count = 0 ; int mid = arr [ N / 2 ] ; for ( int i = 0 ; i < N ; i ++ ) { count += Math . abs ( mid - arr [ i ] ) / D ; } System . out . println ( count ) ; } public static void main ( String [ ] args ) { int N = 4 , D = 2 ; int arr [ ] = { 2 , 4 , 6 , 8 } ; numOperation ( arr , N , D ) ; } }