Skip to content

Commit 734e79d

Browse files
committed
1534. Count Good Triplets: AC
1 parent a626f79 commit 734e79d

File tree

2 files changed

+107
-0
lines changed

2 files changed

+107
-0
lines changed

src/solution/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1156,3 +1156,4 @@ mod s1528_shuffle_string;
11561156
mod s1529_minimum_suffix_flips;
11571157
mod s1530_number_of_good_leaf_nodes_pairs;
11581158
mod s1531_string_compression_ii;
1159+
mod s1534_count_good_triplets;
+106
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
/**
2+
* [1534] Count Good Triplets
3+
*
4+
* Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets.
5+
*
6+
* A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true:
7+
*
8+
*
9+
* 0 <= i < j < k < arr.length
10+
* |arr[i] - arr[j]| <= a
11+
* |arr[j] - arr[k]| <= b
12+
* |arr[i] - arr[k]| <= c
13+
*
14+
*
15+
* Where |x| denotes the absolute value of x.
16+
*
17+
* Return the number of good triplets.
18+
*
19+
*
20+
* Example 1:
21+
*
22+
*
23+
* Input: arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3
24+
* Output: 4
25+
* Explanation: There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)].
26+
*
27+
*
28+
* Example 2:
29+
*
30+
*
31+
* Input: arr = [1,1,2,2,3], a = 0, b = 0, c = 1
32+
* Output: 0
33+
* Explanation: No triplet satisfies all conditions.
34+
*
35+
*
36+
*
37+
* Constraints:
38+
*
39+
*
40+
* 3 <= arr.length <= 100
41+
* 0 <= arr[i] <= 1000
42+
* 0 <= a, b, c <= 1000
43+
*
44+
*/
45+
pub struct Solution {}
46+
47+
// problem: https://leetcode.com/problems/count-good-triplets/
48+
// discuss: https://leetcode.com/problems/count-good-triplets/discuss/?currentPage=1&orderBy=most_votes&query=
49+
50+
// submission codes start here
51+
52+
impl Solution {
53+
pub fn count_good_triplets(arr: Vec<i32>, a: i32, b: i32, c: i32) -> i32 {
54+
let mut counter = 0;
55+
let l = arr.len();
56+
57+
arr[..l - 2].iter().enumerate().for_each(|(i, &ai)| {
58+
arr[..l - 1]
59+
.iter()
60+
.enumerate()
61+
.skip(i + 1)
62+
.filter(|(_, aj)| (ai - **aj).abs() <= a)
63+
.for_each(|(j, &aj)| {
64+
arr[j + 1..l]
65+
.iter()
66+
.filter(|&&ak| (aj - ak).abs() <= b && (ai - ak).abs() <= c)
67+
.for_each(|_| {
68+
counter += 1;
69+
})
70+
})
71+
});
72+
73+
counter
74+
}
75+
}
76+
77+
// submission codes end
78+
79+
#[cfg(test)]
80+
mod tests {
81+
use super::*;
82+
83+
#[test]
84+
fn test_1534_example_1() {
85+
let arr = vec![3, 0, 1, 1, 9, 7];
86+
let a = 7;
87+
let b = 2;
88+
let c = 3;
89+
90+
let result = 4;
91+
92+
assert_eq!(Solution::count_good_triplets(arr, a, b, c), result);
93+
}
94+
95+
#[test]
96+
fn test_1534_example_2() {
97+
let arr = vec![1, 1, 2, 2, 3];
98+
let a = 0;
99+
let b = 0;
100+
let c = 1;
101+
102+
let result = 0;
103+
104+
assert_eq!(Solution::count_good_triplets(arr, a, b, c), result);
105+
}
106+
}

0 commit comments

Comments
 (0)