Given 2 sorted arrays A and B of size N each. Print the sum of the middle elements of the array obtained after merging the given arrays.
Examples:
Input: arr1: 1 2 4 6 10 Input: arr2: 4 5 6 9 12 Output: 11 (5 + 6)
The approach is similar to that of Merge function of Merge Sort. We will merge the given arrays into a vector in sorted form. Since the size of both arrays is the same ‘n’, the middle elements would be at index ‘n-1’ and ‘n’. Add them and return.
C++ Implementation:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
// for multiple test cases
while (t--)
{
int n;
cin >> n;
int arr1[n], arr2[n];
vector<int> v;
// input two arrays separately
for (int i = 0; i < n; i++)
{
cin >> arr1[i];
}
for (int i = 0; i < n; i++)
{
cin >> arr2[i];
}
int i = 0, j = 0;
// Compare elements of both arrays and store
// in sorted format in a vector
while (i < n and j < n)
{
if (arr1[i] > arr2[j])
{
v.push_back(arr2[j]);
j++;
}
else
{
v.push_back(arr1[i]);
i++;
}
}
// Adding middle elements of vector
cout << v[n - 1] + v[n] << endl;
}
return 0;
}
Time Complexity: O(N)
