Maximum OR sum of sub-arrays of two different arrays in C++

C++Server Side ProgrammingProgramming

<h2>Problem statement</h2><p>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.</p><h2>Example</h2><p>If arr1[] = {1, 2, 4, 3, 2} and</p><p>Arr2[] = {1, 3, 3, 12, 2} then maximum result is obtained when we create following two subarrays &minus;</p><p>Subarr1[] = {2, 4, 3} and</p><p>Subarr2[] = {3, 3, 12}</p><h2>Algorithm</h2><p>We can use below formula to gets result &minus;</p><pre class="result notranslate">f(a, 1, n) + f(b, 1, n)</pre><h2>Example</h2><p><a class="demo" href="http://tpcg.io/SO0FeeKk" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">#include &lt;bits/stdc++.h&gt; using namespace std; int getMaximumSum(int *arr1, int *arr2, int n) { &nbsp; &nbsp;int sum1 = 0; &nbsp; &nbsp;int sum2 = 0; &nbsp; &nbsp;for (int i = 0; i &lt; n; ++i) { &nbsp; &nbsp; &nbsp; sum1 = sum1 | arr1[i]; &nbsp; &nbsp; &nbsp; sum2 = sum2 | arr2[i]; &nbsp; &nbsp;} &nbsp; &nbsp;return sum1 + sum2; } int main() { &nbsp; &nbsp;int arr1[] = {1, 2, 4, 3, 2}; &nbsp; &nbsp;int arr2[] = {1, 3, 3, 12, 2}; &nbsp; &nbsp;int n = sizeof(arr1) / sizeof(arr1[0]); &nbsp; &nbsp;cout &lt;&lt; &quot;Maximum result = &quot; &lt;&lt; getMaximumSum(arr1, arr2, n) &lt;&lt; endl; &nbsp; &nbsp;return 0; }</pre><h2>Output</h2><p>When you compile and execute above program. It generates following output &minus;</p><pre class="result notranslate">Maximum result = 22</pre>
raja
Updated on 10-Jan-2020 08:04:03

Advertisements