Maximize the bitwise OR of an 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
function maxOR ( arr , n , k , x ) { let preSum = new Array ( n + 1 ) ; let suffSum = new Array ( n + 1 ) ; let res = 0 , pow = 1 ; for ( let i = 0 ; i < k ; i ++ ) pow *= x ; preSum [ 0 ] = 0 ; for ( let i = 0 ; i < n ; i ++ ) preSum [ i + 1 ] = preSum [ i ] | arr [ i ] ; suffSum [ n ] = 0 ; for ( let i = n - 1 ; i >= 0 ; i -- ) suffSum [ i ] = suffSum [ i + 1 ] | arr [ i ] ; res = 0 ; for ( let i = 0 ; i < n ; i ++ ) res = Math . max ( res , preSum [ i ] | ( arr [ i ] * pow ) suffSum [ i + 1 ] ) ; return res ; } let arr = [ 1 , 2 , 4 , 8 ] ; let n = 4 ; let k = 2 , x = 3 ; let ans = maxOR ( arr , n , k , x ) ; document . write ( ans ) ;