-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCount the number of possible triangles.cpp
60 lines (49 loc) · 1.26 KB
/
Count the number of possible triangles.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
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
public:
// Function to count the number of possible triangles.
int countTriangles(vector<int>& arr) {
// code here
int n = arr.size();
sort(arr.begin(), arr.end());
int count = 0;
for (int i = n - 1; i >= 2; i--) {
int left = 0;
int right = i - 1;
while (left < right) {
if (arr[left] + arr[right] > arr[i]) {
count += (right - left);
right--;
}
else {
left++;
}
}
}
return count;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
cin.ignore(); // To ignore the newline after the integer input
while (t--) {
int n;
vector<int> a;
string input;
// Input format: first number n followed by the array elements
getline(cin, input);
stringstream ss(input);
int num;
while (ss >> num)
a.push_back(num);
Solution obj;
cout << obj.countTriangles(a) << "\n~\n";
}
return 0;
}
// } Driver Code Ends