Make all array elements equal by reducing array elements to half minimum number of times | Java program to implement 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
import java . io . * ; import java . util . * ; class GFG { static void minOperations ( int [ ] arr , int N ) { HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { int res = arr [ i ] ; if ( mp . containsKey ( res ) ) mp . put ( res , mp . get ( res ) + 1 ) ; else mp . put ( res , 1 ) ; res /= 2 ; } int mx = 1 ; for ( Map . Entry < Integer , Integer > it : mp . entrySet ( ) ) { if ( it . getValue ( ) == N ) { mx = it . getKey ( ) ; } } int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int res = arr [ i ] ; while ( res != mx ) { ans ++ ; res /= 2 ; } } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 1 , 1 , 3 } ; int N = arr . length ; minOperations ( arr , N ) ; } }