Minimum value of X to make all array elements equal by either decreasing or increasing by X | C ++ program to implement the above 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinimumX ( int a [ ] , int n ) { set < int > st ; for ( int i = 0 ; i < n ; i ++ ) st . insert ( a [ i ] ) ; if ( st . size ( ) == 1 ) return 0 ; if ( st . size ( ) == 2 ) { int el1 = * st . begin ( ) ; int el2 = * st . rbegin ( ) ; if ( ( el2 - el1 ) % 2 == 0 ) return ( el2 - el1 ) / 2 ; else return ( el2 - el1 ) ; } if ( st . size ( ) == 3 ) { auto it = st . begin ( ) ; int el1 = * it ; it ++ ; int el2 = * it ; it ++ ; int el3 = * it ; if ( ( el2 - el1 ) == ( el3 - el2 ) ) return el2 - el1 ; else return -1 ; } return -1 ; } int main ( ) { int a [ ] = { 1 , 4 , 4 , 7 , 4 , 1 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << findMinimumX ( a , n ) ; return 0 ; }