forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
target_sum_triplets.cpp
56 lines (49 loc) · 1.38 KB
/
target_sum_triplets.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
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
//triplets printing function
void printtriplets(int* arr,int n,int sum)
{
//sorting array initially
sort(arr,arr+n);
cout<<"The triplet sets are:"<<endl;
for(int i =0;i<n-1;i++)
{
int left=i+1;
int right=n-1;
int current=arr[i];
while (left < right)
{
if (current + arr[left] + arr[right] == sum)
{
// Print elements if it's sum is given sum.
//printing elements in ascending order
cout<<current<<", "<<arr[left]<<" and "<<arr[right]<<endl;
left++;
right--;
}
// If current sum is less than 'sum' then increment the left index
else if (current + arr[left] + arr[right] < sum)
left++;
// if current sum is greater than 'sum', then decrement the right index
else
right--;
}
}
}
//Main function
int main()
{
int end,target;
cout<<"Enter the no. of elements in array you want to enter"<<endl;
cin >> end;
int* input = new int[end];
cout<<"Enter elements"<<endl;
for(int ind=0;ind<end;ind++)
cin >> input[ind];
cout<<"Enter target"<<endl;
cin>>target;
printtriplets(input,end,target);
delete[] input;
return 0;
}