-
Notifications
You must be signed in to change notification settings - Fork 10
/
03_target_sum_pairs.cpp
74 lines (58 loc) · 1.78 KB
/
03_target_sum_pairs.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
Array - Target Sum Pairs
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: The first line contains input N.
Next N lines contains the elements of array and (N+1)th line contains target number.
Constraints: Length of the arrays should be between 1 and 1000.
Output Format: Print all the pairs of numbers which sum to target. Print each pair in increasing order.
Sample Input: 5
1
3
4
2
5
5
Sample Output: 1 and 4
2 and 3
Explanation: Find any pair of elements in the array which has sum equal to target element and print them.
*/
#include <iostream>
#include <algorithm>
using namespace std;
void targetSum(int arr[], int range, int target){
// sorting array
sort(arr, arr+range);
int start = 0;
int end = range-1;
while(start<end){
int sum = arr[start] + arr[end];
if(sum == target){
cout << arr[start] << " and " << arr[end] << endl;
start++;
end--;
}else if(sum < target){
start++;
}else{
end--;
}
}
}
int main() {
int range;
cout << "Enter array range: ";
cin >> range;
int arr[range];
cout << "Enter array elements: ";
for(int idx=0; idx<=range-1; idx++){
cin >> arr[idx];
}
int target;
cout << "Enter Target value: ";
cin >> target;
cout << "All pairs of numbers which sum to target : \n";
targetSum(arr, range, target);
return 0;
}