Maximise the OR Sum

Posted: 23 Jun, 2021
Difficulty: Easy

PROBLEM STATEMENT

Try Problem

You are given two arrays of the positive integers. You are required to select two sub-arrays of equal length, one from each array, such that the sum of the OR of two sub-arrays is maximum. Your task is to return the maximum sum possible.

An array ‘C’ is a subarray of array ‘D’ if ‘C’ can be obtained from ‘D’ by deletion of several elements from the beginning and several elements from the end.

Example : let ‘arr’ = [1,0,0] then the possible subarrays of ‘arr’ will be- {1}, {0},{0},{1,0},{0,0},{1,0,0}.

For Example:
Let the first array be : ‘arr1’ = {1,5,8,4} and the second array be ‘arr2’ = {3,7,16,1}

For this, the maximum sum takes the sub-array {5,8} from the first ‘arr1’ and {7,16} from arrays, two, the OR sum will be 13 + 23 = 26, which is maximum.
Input Format:
The first line contains a single integer ‘T’ denoting the number of test cases to be run. Then the test cases follow.

The first line of each test case contains an integer ‘N’ denoting the number of elements in the array.

The second line contains ‘N’ space-separated integers denoting the elements of the first array.

The third line contains ‘N’ space-separated integers denoting the elements of the second array.
Output Format:
For each test case, print an integer denoting the maximum OR sum.

Output for each test case will be printed in a separate line.
Note:
You are not required to print anything; it has already been taken care of. Just implement the function.
Constraints:
1 <= T <= 10
1 <= N <= 10^5
1 <= arr1[i], arr2[i] <= 10^5

Time Limit: 1 sec.
Approach 1

Find the OR sum of both arrays and add them as the logical OR of two Numbers is always greater than or equal to the two numbers.

 

Algorithm :

 

  1. Declare two variables ‘SUM1’ and ‘SUM2’ of type integer and initialize them with 0.
  2. Iterate from 0 to ‘N’ - 1 on both arrays i.e. ‘ARR1’ and ‘ARR2’. (say iterator be i).
    1. Update ‘SUM1’ as ‘SUM1’ = ‘SUM1’ | ‘ARR1[i]’.
    2. Update ‘SUM2’ as ‘SUM2’ = ‘SUM2’ | ‘ARR2[i]’.
  3. Return ‘SUM1’ + ‘SUM2’.
Try Problem