-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCountTriplets.cpp
57 lines (54 loc) · 1.04 KB
/
CountTriplets.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
// Count the triplets
// https://practice.geeksforgeeks.org/problems/count-the-triplets/0
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void solve()
{
int triplets_count = 0;
int N;
vector<int> arr;
cin >> N;
for (int i = 0; i < N; i++)
{
int temp;
cin >> temp;
arr.push_back(temp);
}
sort(arr.begin(), arr.end());
for (int i = N - 1; i > 1; i--)
{
int j = 0, k = i - 1;
while (j != k && (j < k))
{
int sum = arr[j] + arr[k];
if (sum == arr[i])
{
triplets_count++;
j++;
k--;
}
else if (sum > arr[i])
{
k--;
}
else
{
j++;
}
}
}
triplets_count = triplets_count == 0 ? -1 : triplets_count;
cout << triplets_count << endl;
}
int main()
{
int T;
cin >> T;
while (T--)
{
solve();
}
return 0;
}