Created
June 4, 2020 05:20
-
-
Save Ch-sriram/d562c162c1365e253e2612e6281d1f7f to your computer and use it in GitHub Desktop.
Sum of Pairs: Given an array of integers and a number K, check if there exist a pair of indices i,j s.t. a[i] + a[j] = K and i!=j.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <vector> | |
| #include <iostream> | |
| #include <algorithm> | |
| using namespace std; | |
| string sum_pair(vector<int> &ar, const int k) { | |
| sort(ar.begin(), ar.end()); | |
| for(int i = 0, j = ar.size()-1, sum = ar[i] + ar[j]; i < j; sum = ar[i] + ar[j]) { | |
| if(sum == k) return "True"; | |
| else if(sum < k) ++i; | |
| else --j; | |
| } | |
| return "False"; | |
| } | |
| int main() { | |
| int t; cin >> t; | |
| while(t--) { | |
| int n, k; cin >> n >> k; | |
| vector<int> ar(n); | |
| for(int i = 0; i < n; ++i) | |
| cin >> ar[i]; | |
| cout << sum_pair(ar, k) << endl; | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment