Minimize deviation of an array by given operations | Function to find the minimum deviation of the array A [ ] ; Store all array elements in sorted order ; Odd number are transformed using 2 nd operation ; ( Maximum - Minimum ) ; Check if the size of set is > 0 and the maximum element is divisible by 2 ; Maximum element of the set ; Erase the maximum element ; Using operation 1 ; ( Maximum - Minimum ) ; Print the Minimum Deviation Obtained ; Driver Code ; Function Call to find Minimum Deviation of A [ ]
function minimumDeviation ( A , N ) { var s = new Set ( ) ; for ( var i = 0 ; i < N ; i ++ ) { if ( A [ i ] % 2 == 0 ) s . add ( A [ i ] ) ; else s . add ( 2 * A [ i ] ) ; } var tmp = [ ... s ] . sort ( ( a , b ) => a - b ) ; var diff = tmp [ tmp . length - 1 ] - tmp [ 0 ] ; while ( s . size && tmp [ tmp . length - 1 ] % 2 == 0 ) { var maxEl = tmp [ tmp . length - 1 ] ; s . delete ( maxEl ) ; s . add ( parseInt ( maxEl / 2 ) ) ; tmp = [ ... s ] . sort ( ( a , b ) => a - b ) ; diff = Math . min ( diff , tmp [ tmp . length - 1 ] - tmp [ 0 ] ) ; } document . write ( diff ) ; } var A = [ 4 , 1 , 5 , 20 , 3 ] ; var N = A . length ; minimumDeviation ( A , N ) ;