Maximize the bitwise OR of an array | C ++ program to maximize the Bitwise OR Sum in given array ; Function to maximize the bitwise OR sum ; Compute x ^ k ; Find prefix bitwise OR ; Find suffix bitwise OR ; Find maximum OR value ; Drivers code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxOR ( long long arr [ ] , int n , int k , int x ) { long long preSum [ n + 1 ] , suffSum [ n + 1 ] ; long long res , pow = 1 ; for ( int i = 0 ; i < k ; i ++ ) pow *= x ; preSum [ 0 ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) preSum [ i + 1 ] = preSum [ i ] | arr [ i ] ; suffSum [ n ] = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) suffSum [ i ] = suffSum [ i + 1 ] | arr [ i ] ; res = 0 ; for ( int i = 0 ; i < n ; i ++ ) res = max ( res , preSum [ i ] | ( arr [ i ] * pow ) suffSum [ i + 1 ] ) ; return res ; } int main ( ) { long long arr [ ] = { 1 , 2 , 4 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 , x = 3 ; cout << maxOR ( arr , n , k , x ) << " STRNEWLINE " ; return 0 ; }