Closest or Equal Pair to a Given x (Two Pointer Technique)

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n, m, x;

    cout << "Enter First Array Size :: ";
    cin >> n;

    vector<int>a(n);

    cout << "\nEnter First Array Element :: ";
    for(int i=0; i<n; i++)
        cin >> a[i];

    cout << "\nEnter Second Array Size :: ";
    cin >> m;

    vector<int>b(m);

    cout << "\nEnter Second Array Element :: ";
    for (int i=0; i<m; i++)
        cin >> b[i];

    cout << "\nEnter Which Element you want :: ";
    cin >> x;

    sort(a.begin(), a.end());
    sort(b.begin(), b.end());

    int difference = INT_MAX, i = 0, j = m-1, first = -1, second = -1, f = 0;

    while(i<n && j>=0)
    {
        if(abs(a[i] + b[j] - x) < difference)
        {
            f = 1;
            first = i;
            second = j;

            difference = abs(a[i] + b[j] - x);
        }

        if(difference == 0)
        {
            f = 2;
            break;
        }

        if(a[i] + b[j] > x)
            j--;
        else
            i++;
    }

if(f == 1)
cout << "\nClosest Pair are :: " << a[first] << " and " << b[second] << "\n";

else if(f == 2)
cout << "\nEqual Pair are :: " << a[first] << " and " << b[second] << "\n";

else
cout << "\nPair Not Found." << "\n";

    return 0;
}

Comments