Maximum sum of a subsequence whose Bitwise AND is non | C ++ program for the above approach ; Function to find the maximum sum of a subsequence whose Bitwise AND is non - zero ; Stores the resultant maximum sum of the subsequence ; Iterate over all the bits ; Stores the sum of array elements whose i - th bit is set ; Traverse the array elements ; If the bit is set , then add its value to the sum ; Update the resultant maximum sum ; Return the maximum sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumSum ( int arr [ ] , int N ) { int ans = 0 ; for ( int bit = 0 ; bit < 32 ; bit ++ ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] & ( 1 << bit ) ) { sum += arr [ i ] ; } } ans = max ( ans , sum ) ; } return ans ; } int main ( ) { int arr [ ] = { 5 , 4 , 1 , 7 , 11 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maximumSum ( arr , N ) ; return 0 ; }