-
Notifications
You must be signed in to change notification settings - Fork 1
/
TargetSumPairs.cpp
54 lines (50 loc) · 1.23 KB
/
TargetSumPairs.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
51
52
53
54
/*
Take as input N, the size of array. Take N more inputs and store that in an array. Take as input “target”, a number. Write a function which prints all pairs of numbers which sum to target.
Input Format:
Constraints:
Length of the arrays should be between 1 and 1000.
Output Format
Sample Input
5
1
3
4
2
5
5
Sample Output
1 and 4
2 and 3
approach:
sort the array
make another array with values 1 or 0 indicating whether the values has been used or not
check for target pairs[start the initial loop from behind, which will check for all values starting from 0 to n - 1// that number?(if available)]
change value in other array accordingly, and print simultaneously.
*/
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
int arr[1000], target, numOfElements;
cin >> numOfElements;
for(int i = 0; i < numOfElements; i++){
cin >> arr[i];
}
cin >> target;
sort(arr, arr + numOfElements);
int left = 0, right = numOfElements - 1;
while(left < right){
if(arr[left] + arr[right] == target){
cout << arr[left] << " and " << arr[right] << endl;
left++;
right--;
}
else if(arr[left] + arr[right] > target){
right--;
}
else{
left++;
}
}
return 0;
}