Maximize count of 1 s in an array by repeated division of array elements by 2 at most K times | Java program for the above approach ; Function to count the maximum number of array elements that can be reduced to 1 by repeatedly dividing array elements by 2 ; Sort the array in ascending order ; Store the count of array elements ; Traverse the array ; Store the number of operations required to reduce arr [ i ] to 1 ; Decrement k by opr ; If k becomes less than 0 , then break out of the loop ; Increment cnt by 1 ; Print the answer ; Driver Code
import java . util . * ; public class GFG { static void findMaxNumbers ( int arr [ ] , int n , int k ) { Arrays . sort ( arr ) ; int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int opr = ( int ) Math . ceil ( ( Math . log ( arr [ i ] ) / Math . log ( 2 ) ) ) ; k -= opr ; if ( k < 0 ) { break ; } cnt ++ ; } System . out . println ( cnt ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 5 , 8 , 4 , 7 } ; int N = arr . length ; int K = 5 ; findMaxNumbers ( arr , N , K ) ; } }