C++ program to find two numbers from two arrays whose sum is not present in both arrays


Suppose we have two arrays A with n elements and B with m elements. Select some element a form A and some element b from B, such that a + b does not belong to A or B.

So, if the input is like A = [3, 2, 2]; B = [1, 5, 7, 7, 9], then the output will be [3, 1], because 3 + 1 = 4 is not present in any array. (Other answers are also available)

Steps

To solve this, we will follow these steps −

sort the array A
sort the array B
return last element of A and last element of B

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

void solve(vector<int> A, vector<int> B) {
   sort(A.begin(), A.end());
   sort(B.begin(), B.end());
   cout << A[A.size() - 1] << ", " << B[B.size() - 1];
}
int main() {
   vector<int> A = { 3, 2, 2 };
   vector<int> B = { 1, 5, 7, 7, 9 };
   solve(A, B);
}

Input

{ 3, 2, 2 }, { 1, 5, 7, 7, 9 }

Output

3, 9

Updated on: 03-Mar-2022

94 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements