Smallest positive integer K such that all array elements can be made equal by incrementing or decrementing by at most K | Java program for the above approach ; Function to find smallest integer K such that incrementing or decrementing each element by K at most once makes all elements equal ; Store distinct array elements ; Traverse the array , A [ ] ; Count elements into the set ; If M is greater than 3 ; If M is equal to 3 ; Stores the first smallest element ; Stores the second smallest element ; Stores the largest element ; IF difference between B_2 and B_1 is equal to B_3 and B_2 ; If M is equal to 2 ; Stores the smallest element ; Stores the largest element ; If difference is an even ; If M is equal to 1 ; Driver code ; Given array ; Given size ; Print the required smallest integer
import java . io . * ; import java . util . * ; class GFG { static void findMinKToMakeAllEqual ( int N , int A [ ] ) { Set < Integer > B = new HashSet < Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { B . add ( A [ i ] ) ; } ArrayList < Integer > b = new ArrayList < Integer > ( B ) ; int M = b . size ( ) ; int i = 0 ; if ( M > 3 ) { System . out . print ( " - 1" ) ; } else if ( M == 3 ) { int B_1 = b . get ( i ++ ) ; int B_2 = b . get ( i ++ ) ; int B_3 = b . get ( i ++ ) ; if ( B_2 - B_1 == B_3 - B_2 ) { System . out . print ( B_2 - B_1 ) ; } else { System . out . print ( " - 1" ) ; } } else if ( M == 2 ) { int B_1 = b . get ( i ++ ) ; int B_2 = b . get ( i ++ ) ; if ( ( B_2 - B_1 ) % 2 == 0 ) { System . out . print ( ( B_2 - B_1 ) / 2 ) ; } else { System . out . print ( B_2 - B_1 ) ; } } else { System . out . print ( 0 ) ; } } public static void main ( String [ ] args ) { int A [ ] = { 1 , 3 , 5 , 1 } ; int N = A . length ; findMinKToMakeAllEqual ( N , A ) ; } }