给定两个正整数数组。从每个阵列中选择两个大小相等的子阵列,然后计算两个子阵列的最大可能OR值。
注意:令f(x,l,r)是数组x中[l,r]范围内所有元素的OR和。
例子 :
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
观察按位OR运算符。如果我们取两个整数X和Y,则(X | Y> = X)。可以通过一些例子来证明。让我们使用以上方程式得出一个公式。
并且
根据以上两个方程,
因此,当我们对整个数组进行“或”运算时,我们将得到最大的总和。
下面是上述方法的实现:
C++
// CPP program to find maximum OR sum
#include
using namespace std;
// function to find maximum OR sum
void MaximumSum(int a[], int b[], int n)
{
int sum1 = 0, sum2 = 0;
// OR sum of all the elements
// in both arrays
for (int i = 0; i < n; i++) {
sum1 |= a[i];
sum2 |= b[i];
}
cout << sum1 + sum2 << endl;
}
// Driver Code
int main()
{
int A[] = { 1, 2, 4, 3, 2 };
int B[] = { 2, 3, 3, 12, 1 };
int n = sizeof(A) / sizeof(A[0]);
MaximumSum(A, B, n);
return 0;
}
Java
// Java program to find maximum OR sum
class GFG {
// function to find maximum OR sum
static void MaximumSum(int a[], int b[], int n)
{
int sum1 = 0, sum2 = 0;
// OR sum of all the elements
// in both arrays
for (int i = 0; i < n; i++) {
sum1 |= a[i];
sum2 |= b[i];
}
System.out.println(sum1 + sum2);
}
// Driver code
public static void main(String arg[])
{
int A[] = {1, 2, 4, 3, 2};
int B[] = {2, 3, 3, 12, 1};
int n = A.length;
MaximumSum(A, B, n);
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python 3 program to
# find maximum OR sum
# function to find
# maximum OR sum
def MaximumSum(a, b, n):
sum1 = 0
sum2 = 0
# OR sum of all the
# elements in both arrays
for i in range(0, n):
sum1 |= a[i]
sum2 |= b[i]
print(sum1 + sum2)
# Driver Code
A = [ 1, 2, 4, 3, 2 ]
B = [ 2, 3, 3, 12, 1 ]
n = len(A)
MaximumSum(A, B, n)
# This code is contributed by Smitha Dinesh Semwal
C#
// C# program to find maximum OR sum
using System;
class GFG {
// function to find maximum OR sum
static void MaximumSum(int []a, int []b, int n)
{
int sum1 = 0, sum2 = 0;
// OR sum of all the elements
// in both arrays
for (int i = 0; i < n; i++)
{
sum1 |= a[i];
sum2 |= b[i];
}
Console.WriteLine(sum1 + sum2);
}
// Driver code
public static void Main()
{
int []A = {1, 2, 4, 3, 2};
int []B = {2, 3, 3, 12, 1};
int n = A.Length;
MaximumSum(A, B, n);
}
}
// This code is contributed by Vt_m.
PHP
Javascript
输出 :
22