1534. Count Good Triplets #1558
-
Topics: Given an array of integers A triplet
Where Return the number of good triplets. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to count the number of good triplets in an array. A triplet is considered good if it meets specific conditions involving absolute differences between elements at different indices. Approach
Let's implement this solution in PHP: 1534. Count Good Triplets <?php
/**
* @param Integer[] $arr
* @param Integer $a
* @param Integer $b
* @param Integer $c
* @return Integer
*/
function countGoodTriplets($arr, $a, $b, $c) {
$count = 0;
$n = count($arr);
for ($i = 0; $i < $n - 2; $i++) {
for ($j = $i + 1; $j < $n - 1; $j++) {
$diff_ij = abs($arr[$i] - $arr[$j]);
if ($diff_ij > $a) {
continue;
}
for ($k = $j + 1; $k < $n; $k++) {
$diff_jk = abs($arr[$j] - $arr[$k]);
if ($diff_jk > $b) {
continue;
}
$diff_ik = abs($arr[$i] - $arr[$k]);
if ($diff_ik <= $c) {
$count++;
}
}
}
}
return $count;
}
// Example 1
$arr1 = array(3, 0, 1, 1, 9, 7);
$a1 = 7;
$b1 = 2;
$c1 = 3;
echo "Output 1: " . countGoodTriplets($arr1, $a1, $b1, $c1) . "\n"; // Output: 4
// Example 2
$arr2 = array(1, 1, 2, 2, 3);
$a2 = 0;
$b2 = 0;
$c2 = 1;
echo "Output 2: " . countGoodTriplets($arr2, $a2, $b2, $c2) . "\n"; // Output: 0
?> Explanation:
This approach ensures that we efficiently check all possible triplets while adhering to the problem constraints, making it both effective and straightforward. |
Beta Was this translation helpful? Give feedback.
We need to count the number of good triplets in an array. A triplet is considered good if it meets specific conditions involving absolute differences between elements at different indices.
Approach