-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGFG_TripletSumWithGivenRange.cpp
58 lines (50 loc) · 1.31 KB
/
GFG_TripletSumWithGivenRange.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
/*
https://practice.geeksforgeeks.org/problems/triplets-with-sum-with-given-range/1/#
Triplets with sum with given range
*/
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution {
public:
int countTriplets(int Arr[], int N, int L, int R) {
sort(Arr, Arr+N);
if(N<3) return 0;
int low, high, cnt;
function<int(int)> count_diff = [&](int T)->int{
cnt=0;
for(int i=0; i<N-2; i++)
{
low = i+1;
high = N-1;
while(low<high)
{
if(Arr[i]+Arr[low]+Arr[high] > T)
high--;
else
cnt += high-low, low++;
}
}
return cnt;
};
return count_diff(R)-count_diff(L-1);
}
};
// { Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int N;
cin >> N;
int Arr[N];
for (int i = 0; i < N; i++) cin >> Arr[i];
int L, R;
cin >> L >> R;
Solution obj;
cout << obj.countTriplets(Arr, N, L, R) << endl;
}
return 0;
} // } Driver Code Ends