Make all array elements equal by reducing array elements to half minimum number of times | Function to find minimum number of operations ; Initialize map ; Traverse the array ; Divide current array element until it reduces to 1 ; Traverse the map ; Find the maximum element having frequency equal to N ; Stores the minimum number of operations required ; Count operations required to convert current element to mx ; Print the answer ; Given array ; Size of the array
function minOperations ( arr , N ) { var mp = new Map ( ) ; for ( var i = 0 ; i < N ; i ++ ) { var res = arr [ i ] ; while ( res ) { if ( mp . has ( res ) ) { mp . set ( res , mp . get ( res ) + 1 ) ; } else { mp . set ( res , 1 ) ; } res = parseInt ( res / 2 ) ; } } var mx = 1 ; mp . forEach ( ( value , key ) => { if ( value == N ) { mx = key ; } } ) ; var ans = 0 ; for ( var i = 0 ; i < N ; i ++ ) { var res = arr [ i ] ; while ( res != mx ) { ans ++ ; res = parseInt ( res / 2 ) ; } } document . write ( ans ) ; } var arr = [ 3 , 1 , 1 , 3 ] ; var N = arr . length ; minOperations ( arr , N ) ;