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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( int arr [ ] , int N ) { map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { int res = arr [ i ] ; while ( res ) { mp [ res ] ++ ; res /= 2 ; } } int mx = 1 ; for ( auto it : mp ) { if ( it . second == N ) { mx = it . first ; } } int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int res = arr [ i ] ; while ( res != mx ) { ans ++ ; res /= 2 ; } } cout << ans ; } int main ( ) { int arr [ ] = { 3 , 1 , 1 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minOperations ( arr , N ) ; }