Minimize the maximum difference of any pair by doubling odd elements and reducing even elements by half | Function to minimize the maximum difference between any pair of elements of the array by the given operations ; Traverse the array ; If current element is even ; Insert it into even ; Otherwise ; Make it even by multiplying by 2 and insert it into set ; Calculate difference between first and the last element of the set ; Iterate until difference is minimized ; Erase the current element ; Reduce current element by half and insert it into the Set ; Update difference ; Return the resultant difference ; Driver Code
function minimumMaxDiff ( nums ) { var s = new Set ( ) ; for ( var i = 0 ; i < nums . length ; i ++ ) { if ( nums [ i ] % 2 == 0 ) s . add ( nums [ i ] ) ; else s . add ( nums [ i ] * 2 ) ; } var tmp = [ ... s ] . sort ( ( a , b ) => a - b ) var res = tmp [ tmp . length - 1 ] - tmp [ 0 ] ; while ( tmp [ tmp . length - 1 ] % 2 == 0 ) { var x = tmp [ tmp . length - 1 ] ; s . delete ( x ) ; s . add ( parseInt ( x / 2 ) ) ; tmp = [ ... s ] . sort ( ( a , b ) => a - b ) res = Math . min ( res , tmp [ tmp . length - 1 ] - tmp [ 0 ] ) ; } return res ; } var arr = [ 1 , 2 , 5 , 9 ] ; document . write ( minimumMaxDiff ( arr ) ) ;