Pair Sums

You have been given an integer array A and a number K. Now, you need to find out whether any two different elements of the array A sum to the number K. Two elements are considered to be different if they lie at different positions in the array. If there exists such a pair of numbers, print "YES" (without quotes), else print "NO" without quotes.

Example:

Input:  n = 5, k = 9, a = [1,2,3,4,5]
Output: YES

Approach

C++

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

bool pairSums(int nint kint a[])
{
    int i = 0j = n - 1;
    sort(aa + n);
    int flag = 0;
    while (i < j)
    {
        if (a[i] + a[j] == k)
        {
            flag = 1;
            break;
        }
        else if (a[i] + a[j] > k)
            j--;
        else
            i++;
    }
    if (flag == 1)
        return true;
    else
        return false;
}
int main()
{

    int n = 5k = 9;

    int a[n] = {12345};

    if (pairSums(nka))
        cout << "YES\n";
    else
        cout << "NO\n";

    return 0;
}


No comments:

Post a Comment