
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum or Sum of Sub-Arrays of Two Different Arrays in C++
Problem statement
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.
Example
If arr1[] = {1, 2, 4, 3, 2} and
Arr2[] = {1, 3, 3, 12, 2} then maximum result is obtained when we create following two subarrays −
Subarr1[] = {2, 4, 3} and
Subarr2[] = {3, 3, 12}
Algorithm
We can use below formula to gets result −
f(a, 1, n) + f(b, 1, n)
Example
#include <bits/stdc++.h> using namespace std; int getMaximumSum(int *arr1, int *arr2, int n) { int sum1 = 0; int sum2 = 0; for (int i = 0; i < n; ++i) { sum1 = sum1 | arr1[i]; sum2 = sum2 | arr2[i]; } return sum1 + sum2; } int main() { int arr1[] = {1, 2, 4, 3, 2}; int arr2[] = {1, 3, 3, 12, 2}; int n = sizeof(arr1) / sizeof(arr1[0]); cout << "Maximum result = " << getMaximumSum(arr1, arr2, n) << endl; return 0; }
Output
When you compile and execute above program. It generates following output −
Maximum result = 22
Advertisements