Maximum bitwise OR value of subsequence of length K | C ++ program for the above approach ; Function to convert bit array to decimal number ; Return the final result ; Function to find the maximum Bitwise OR value of subsequence of length K ; Initialize bit array of size 32 with all value as 0 ; Iterate for each index of bit [ ] array from 31 to 0 , and check if the ith value of bit array is 0 ; Check for maximum contributing element ; Update the bit array if max_contributing element is found ; Decrement the value of K ; Return the result ; Driver Code ; Given array arr [ ] ; Length of subsequence ; Function Call
#include <iostream> NEW_LINE using namespace std ; int build_num ( int bit [ ] ) { int ans = 0 ; for ( int i = 0 ; i < 32 ; i ++ ) if ( bit [ i ] ) ans += ( 1 << i ) ; return ans ; } int maximumOR ( int arr [ ] , int n , int k ) { int bit [ 32 ] = { 0 } ; for ( int i = 31 ; i >= 0 ; i -- ) { if ( bit [ i ] == 0 && k > 0 ) { int temp = build_num ( bit ) ; int temp1 = temp ; int val = -1 ; for ( int j = 0 ; j < n ; j ++ ) { if ( temp1 < ( temp arr [ j ] ) ) { temp1 = temp | arr [ j ] ; val = arr [ j ] ; } } if ( val != -1 ) { k -- ; for ( int j = 0 ; j < 32 ; j ++ ) { if ( val & ( 1 << j ) ) bit [ j ] ++ ; } } } } return build_num ( bit ) ; } int main ( ) { int arr [ ] = { 5 , 9 , 7 , 19 } ; int k = 3 ; int n = sizeof arr / sizeof arr [ 0 ] ; cout << maximumOR ( arr , n , k ) ; return 0 ; }