Make all array elements equal by reducing array elements to half minimum number of times | C # program for the above approach ; 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 ; Driver code ; Given array ; Size of the array
using System ; using System . Collections . Generic ; class GFG { static void minOperations ( int [ ] arr , int N ) { Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { int res = arr [ i ] ; while ( res > 0 ) { if ( mp . ContainsKey ( res ) ) { mp [ res ] ++ ; } else { mp [ res ] = 1 ; } res /= 2 ; } } int mx = 1 ; foreach ( KeyValuePair < int , int > it in mp ) { if ( it . Value == N ) { mx = it . Key ; } } int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int res = arr [ i ] ; while ( res != mx ) { ans ++ ; res /= 2 ; } } Console . Write ( ans ) ; } static void Main ( ) { int [ ] arr = { 3 , 1 , 1 , 3 } ; int N = arr . Length ; minOperations ( arr , N ) ; } }