Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets.
A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true:
0 <= i < j < k < arr.length
|arr[i] - arr[j]| <= a
|arr[j] - arr[k]| <= b
|arr[i] - arr[k]| <= c
Where |x| denotes the absolute value of x.
Return the number of good triplets.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: intcountGoodTriplets(vector<int>& arr, int a, int b, int c){ vector<int> pre(1010); int res = 0, n = arr.size(); for(int j = 0; j < n; j++) { for(int k = j + 1; k < n; k++) { if(abs(arr[j] - arr[k]) > b) continue; int mi = max({0,arr[j] - a, arr[k] - c}), ma = min({arr[j] + a, arr[k] + c, 1000}) + 1; if(mi > ma) continue; res += pre[ma] - pre[mi]; }
for(int i = arr[j] + 1; i < pre.size(); i++) pre[i]++; } return res; } };