Member-only story
Leetcode 1534: Count Good Triplets
1 min readAug 3, 2020
In this Leetcode problem, we need to return all the triplets satisfying particular conditions.
Solution
For this problem, we can simply use brute force and try all the potential triplets with i < j < k
.
We use abs
for absolute value to find if the triplets satisfy the conditions.
class Solution {
public:
int countGoodTriplets(vector<int>& arr, int a, int b, int c) {
int res = 0;
int l = arr.size();
for (int i = 0; i < l; i++) {
for (int j = i + 1; j < l; j++) {
if (abs(arr[i] - arr[j]) > a) {
continue;
}
for (int k = j + 1; k < l; k++) {
if (abs(arr[i] - arr[k]) <= c
&& abs(arr[j] - arr[k]) <= b) {
res++;
}
}
}
}
return res;
}
};