-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpairSum.cpp
More file actions
54 lines (46 loc) · 1.25 KB
/
pairSum.cpp
File metadata and controls
54 lines (46 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <vector>
using namespace std;
vector<int> pairSum(vector<int> nums, int targetSum) {
vector<int> result;
int n = nums.size();
int i = 0;
int j = n - 1;
while(i<j){
int pairSum = nums[i] + nums[j];
if(pairSum > targetSum){
j--;
}
else if(pairSum < targetSum){
i++;
}
else{
result.push_back(nums[i]);
result.push_back(nums[j]);
return result; // Return the first found pair
}
}
return result; // Return empty if no pair found
}
int main(){
vector<int> vec;
cout << "Enter number of elements to insert in the vector: ";
int n;
cin >> n;
cout << "Enter the elements of the vector: " << endl;
for(int i = 0; i < n; i++){
int element;
cin >> element;
vec.push_back(element); // Insert elements into the vector
}
int targetSum;
cout << "Enter the target sum: ";
cin >> targetSum;
vector<int> result = pairSum(vec, targetSum);
if(!result.empty()){
cout << "Pair found: " << result[0] << ", " << result[1] << endl;
} else {
cout << "No pair found with the given target sum." << endl;
}
return 0;
}