Maximize count of 1 s in an array by repeated division of array elements by 2 at most K times | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMaxNumbers ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int opr = ceil ( log2 ( arr [ i ] ) ) ; k -= opr ; if ( k < 0 ) { break ; } cnt ++ ; } cout << cnt ; } int main ( ) { int arr [ ] = { 5 , 8 , 4 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 5 ; findMaxNumbers ( arr , N , K ) ; return 0 ; }