Minimum value of X to make all array elements equal by either decreasing or increasing by X | Java implementation of the approach ; Function that returns the minimum value of X ; Declare a set ; Iterate in the array element and insert them into the set ; If unique elements is 1 ; Unique elements is 2 ; Get both el2 and el1 ; Check if they are even ; If there are 3 unique elements ; Get three unique elements ; Check if their difference is same ; More than 3 unique elements ; Driver code
import java . util . HashSet ; import java . util . Iterator ; import java . util . Set ; class GFG { static int findMinimumX ( int a [ ] , int n ) { Set < Integer > st = new HashSet < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) st . add ( a [ i ] ) ; if ( st . size ( ) == 1 ) return 0 ; if ( st . size ( ) == 2 ) { Iterator < Integer > it = st . iterator ( ) ; int el1 = it . next ( ) ; int el2 = it . next ( ) ; if ( ( el2 - el1 ) % 2 == 0 ) return ( el2 - el1 ) / 2 ; else return ( el2 - el1 ) ; } if ( st . size ( ) == 3 ) { Iterator < Integer > it = st . iterator ( ) ; int el1 = it . next ( ) ; int el2 = it . next ( ) ; int el3 = it . next ( ) ; if ( ( el2 - el1 ) == ( el3 - el2 ) ) return el2 - el1 ; else return - 1 ; } return - 1 ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 4 , 4 , 7 , 4 , 1 } ; int n = a . length ; System . out . println ( findMinimumX ( a , n ) ) ; } }