Smallest positive integer K such that all array elements can be made equal by incrementing or decrementing by at most K | 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 ; Given array ; Given size ; Print the required smallest integer
function findMinKToMakeAllEqual ( N , A ) { var B = new Set ( ) ; for ( var i = 0 ; i < N ; i ++ ) B . add ( A [ i ] ) ; var M = B . size ; var itr = [ ... B ] . sort ( ( a , b ) => a - b ) ; if ( M > 3 ) document . write ( " " ) ; else if ( M == 3 ) { var B_1 = itr [ 0 ] ; var B_2 = itr [ 1 ] ; var B_3 = itr [ 2 ] ; if ( B_2 - B_1 == B_3 - B_2 ) document . write ( B_2 - B_1 ) ; else document . write ( " " ) ; } else if ( M == 2 ) { var B_1 = itr [ 0 ] ; var B_2 = itr [ 1 ] ; if ( ( B_2 - B_1 ) % 2 == 0 ) document . write ( parseInt ( ( B_2 - B_1 ) / 2 ) ) ; else document . write ( B_2 - B_1 ) ; } else document . write ( 0 ) ; } var A = [ 1 , 3 , 5 , 1 ] ; var N = A . length ; findMinKToMakeAllEqual ( N , A ) ;