VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-sum-sub-arrays-two-different-arrays/

⇱ Maximum OR sum of sub-arrays of two different arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum OR sum of sub-arrays of two different arrays

Last Updated : 28 Jul, 2022

Given two arrays of positive integers. Select two sub-arrays of equal size from each array and calculate maximum possible OR sum of the two sub-arrays. 

Note: Let f(x, l, r) is the OR sum of all the elements in the range [l, r] in array x. 

Examples : 

Input : A[] = {1, 2, 4, 3, 2}
 B[] = {2, 3, 3, 12, 1}
Output : 22
Explanation: Here, one way to get maximum
sum is to select sub-array [l = 2, r = 4]
f(A, 2, 4) = 2|4|3 = 7
f(B, 2, 4) = 3|3|12 = 15
So, f(A, 2, 4) + f(B, 2, 4) = 7 + 15 = 22.
This sum can be achieved in many other ways.

Input : A[] = {1, 2, 2}
 B[] = {2, 1, 3}
Output : 6

Observe the operation of Bitwise OR operator. If we take two integers X and Y, then (X|Y >= X). It can be proved by taking some examples. Lets derive a formula using the above equation. 

and also 
from the above two equations, 
So, we get maximum sum when we take the OR of the whole array -> 

Below is the implementation of above approach: 


Output
22

Time Complexity: O(n)
Auxiliary Space: O(1)

Comment
Article Tags: