Smallest positive integer K such that all array elements can be made equal by incrementing or decrementing by at most K | C ++ 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 ; Iterator to store first element of B ; 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
#include <iostream> NEW_LINE #include <set> NEW_LINE using namespace std ; void findMinKToMakeAllEqual ( int N , int A [ ] ) { set < int > B ; for ( int i = 0 ; i < N ; i ++ ) B . insert ( A [ i ] ) ; int M = B . size ( ) ; set < int > :: iterator itr = B . begin ( ) ; if ( M > 3 ) printf ( " - 1" ) ; else if ( M == 3 ) { int B_1 = * itr ; int B_2 = * ( ++ itr ) ; int B_3 = * ( ++ itr ) ; if ( B_2 - B_1 == B_3 - B_2 ) printf ( " % d " , B_2 - B_1 ) ; else printf ( " - 1" ) ; } else if ( M == 2 ) { int B_1 = * itr ; int B_2 = * ( ++ itr ) ; if ( ( B_2 - B_1 ) % 2 == 0 ) printf ( " % d " , ( B_2 - B_1 ) / 2 ) ; else printf ( " % d " , B_2 - B_1 ) ; } else printf ( " % d " , 0 ) ; } int main ( ) { int A [ ] = { 1 , 3 , 5 , 1 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; findMinKToMakeAllEqual ( N , A ) ; }