3392. Count Subarrays of Length Three With a Condition #1613
-
Topics: Given an integer array Example 1:
Example 2:
Constraints:
Hint:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to count the number of subarrays of length 3 where the sum of the first and third elements equals exactly half of the second element. Approach
Let's implement this solution in PHP: 3392. Count Subarrays of Length Three With a Condition <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function countSubarrays($nums) {
$count = 0;
$n = count($nums);
for ($i = 0; $i <= $n - 3; $i++) {
$a = $nums[$i];
$b = $nums[$i + 1];
$c = $nums[$i + 2];
if ($b % 2 != 0) {
continue;
}
$half_b = $b / 2;
if (($a + $c) == $half_b) {
$count++;
}
}
return $count;
}
// Example usage:
$nums1 = array(1, 2, 1, 4, 1);
echo countSubarrays($nums1) . "\n"; // Output: 1
$nums2 = array(1, 1, 1);
echo countSubarrays($nums2) . "\n"; // Output: 0
?> Explanation:
This approach ensures we check each subarray in linear time, making the solution efficient given the problem constraints. |
Beta Was this translation helpful? Give feedback.
We need to count the number of subarrays of length 3 where the sum of the first and third elements equals exactly half of the second element.
Approach
n-3
(wheren
is the length of the array), consider the subarray starting at that index with length 3.Le…