-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkey_pair.cpp
50 lines (46 loc) · 968 Bytes
/
key_pair.cpp
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
#include<bits/stdc++.h>
using namespace std;
//brute forrce
// int keypair(int arr[],int n,int x){
// for(int i=0;i<n;i++){
// for(int j=i+1;j<n;j++){
// if(arr[i]+arr[j]==x){
// return 1;
// }
// }
// }
// return 0;
// }
//optimal approach
int twopointer(int arr[],int n,int x){
int l=0;
int h=n-1;
while(l<h){
int csum=arr[l]+arr[h];
if(csum==x){
return arr[l];
}
else if(csum>x){
h--;
}
else{
l++;
}
}
return -1;
}
int keypair(int arr[],int n,int x){
sort(arr,arr+n);
return twopointer(arr,n,x);
}
int main(){
int arr[] = {1, 2, 4, 3, 6};
int n= 5, x = 10;
int result=keypair(arr,n,x);
if(result==-1){
cout<<"no";
}
else{
cout<<"yes"<<result;
}
}