From 92be08029f6d746dcae75c87533840f5b030b610 Mon Sep 17 00:00:00 2001 From: Jack Sangdahl Date: Sun, 13 Apr 2025 22:13:22 -0600 Subject: 1534. count good triplets --- count_good_triplets.c | 29 +++++++++++++++++++++++++++++ count_good_triplets.py | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 count_good_triplets.c create mode 100644 count_good_triplets.py diff --git a/count_good_triplets.c b/count_good_triplets.c new file mode 100644 index 0000000..9275841 --- /dev/null +++ b/count_good_triplets.c @@ -0,0 +1,29 @@ +// 1534. Count Good Triplets +#include "leetcode.h" + +/* + * given an array of integers 'arr', and three integers 'a, b, c', yo need to + * find the number of good triplets. a triplet '(arr[i], arr[j], arr[k])' is + * good if the following conditions are met: '0 <= i < j < k < arr.len, |arr[i] + * - arr[j]| <= (a, b, c)' where '|x|' denotes the absolute value of 'x'. return + * the number of good triplets. + */ + +int countGoodTriplets(int *arr, int arrSize, int a, int b, int c) { + int cnt = 0; + for (int i = 0; i < arrSize - 2; i++) + for (int k = i + 2; k < arrSize; k++) { + if (abs(arr[k] - arr[i]) > c) + continue; + for (int j = i + 1; j < k; j++) + if (abs(arr[i] - arr[j]) <= a && abs(arr[j] - arr[k]) <= b) + ++cnt; + } + return cnt; +} + +int main() { + int a1[] = {3, 0, 1, 1, 9, 7}, a2[] = {1, 1, 2, 2, 3}; + printf("%d\n", countGoodTriplets(a1, ARRAY_SIZE(a1), 7, 2, 3)); // expect: 4 + printf("%d\n", countGoodTriplets(a2, ARRAY_SIZE(a2), 0, 0, 1)); // expect: 0 +} diff --git a/count_good_triplets.py b/count_good_triplets.py new file mode 100644 index 0000000..c3007cf --- /dev/null +++ b/count_good_triplets.py @@ -0,0 +1,36 @@ +# 1534. Count Good Triplets + +""" +given an array of integers 'arr', and three integers 'a, b, c', yo need to +find the number of good triplets. a triplet '(arr[i], arr[j], arr[k])' is +good if the following conditions are met: '0 <= i < j < k < arr.len, |arr[i] +- arr[j]| <= (a, b, c)' where '|x|' denotes the absolute value of 'x'. return +the number of good triplets. +""" + + +class Solution(object): + def countGoodTriplets(self, arr, a, b, c): + """ + :type arr: List[int] + :type a: int + :type b: int + :type c: int + :rtype: int + """ + cnt = 0 + n = len(arr) + for i in range(n - 2): + for k in range(i + 2, n): + if abs(arr[k] - arr[i]) > c: + continue + for j in range(i + 1, k): + if abs(arr[i] - arr[j]) <= a and abs(arr[j] - arr[k]) <= b: + cnt += 1 + return cnt + + +if __name__ == "__main__": + obj = Solution() + print(obj.countGoodTriplets(arr=[3, 0, 1, 1, 9, 7], a=7, b=2, c=3)) + print(obj.countGoodTriplets(arr=[1, 1, 2, 2, 3], a=0, b=0, c=1)) -- cgit v1.2.3