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 n, int k, int a[]){int i = 0, j = n - 1;sort(a, a + n);int flag = 0;while (i < j){if (a[i] + a[j] == k){flag = 1;break;}else if (a[i] + a[j] > k)j--;elsei++;}if (flag == 1)return true;elsereturn false;}int main(){int n = 5, k = 9;int a[n] = {1, 2, 3, 4, 5};if (pairSums(n, k, a))cout << "YES\n";elsecout << "NO\n";return 0;}
No comments:
Post a Comment