-
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathpair_sum_problem.cpp
More file actions
70 lines (56 loc) · 1.07 KB
/
pair_sum_problem.cpp
File metadata and controls
70 lines (56 loc) · 1.07 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
Check if given array consists of pair of element whose sum is equal to the number(k) provided
by the user.
*/
#include<iostream>
#include<algorithm>
using namespace std;
//* worst case complexity: O(n^2)
bool pairs(int arr[], int n, int k)
{
for(int i=0; i<n; i++)
{
for(int j=i+1; j<n-1; j++)
{
if(arr[i]+arr[j]==k)
{
return true;
}
}
}
return false;
}
//* Complexity: O(n)
bool pairs_2(int arr[], int n, int k)
{
sort(arr,arr+n);
int low = 0;
int high = n-1;
while(arr[low] + arr[high] != k && low<high)
{
int val = arr[low] + arr[high];
if(val<k)
low++;
if(val>k)
high--;
if(val==k)
return true;
}
return false;
}
int main()
{
cout<<"Length of array: "<<endl;
int n;
cin>>n;
int arr[n];
for(int i=0; i<n; i++)
{
cin>>arr[i];
}
cout<<"Enter value k: "<<endl;
int k;
cin>>k;
cout<<pairs(arr,n,k)<<endl;
return 0;
}