-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGFG_TripletsSumSmallerThanX.cpp
79 lines (58 loc) · 1.33 KB
/
GFG_TripletsSumSmallerThanX.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
75
76
77
78
79
/*
https://practice.geeksforgeeks.org/problems/count-triplets-with-sum-smaller-than-x5549/1#
Count triplets with sum smaller than X
*/
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution{
public:
long long countTriplets(long long arr[], int n, long long sum)
{
sort(arr, arr+n);
if(n<3) return 0;
long long cnt = 0, min_sum;
int l, r ;
for(int i=0; i<n-2; i++)
{
l = i+1;
r = n-1;
while(l<r)
{
min_sum = arr[i]+arr[l]+arr[r];
if(min_sum < sum)
{
cnt+=r-l;
l++;
}
else //if(min_sum > sum)
{
r--;
}
}
}//for i
return cnt;
}
};
// { Driver Code Starts.
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
long long sum;
cin>>n>>sum;
long long arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
Solution ob;
cout << ob.countTriplets(arr, n, sum) ;
cout << "\n";
}
return 0;
}
// } Driver Code Ends