[LeetCode] Count Subarrays of Length Three With a Condition

3392. Count Subarrays of Length Three With a Condition

Given an integer array nums, return the number of subarrays of length 3 such that the sum of the first and third numbers equals exactly half of the second number.

A subarray is a contiguous non-empty sequence of elements within an array.

1
2
3
4
5
6
7
8
9
10
func countSubarrays(nums []int) int {
res := 0
n := len(nums)
for i := 0; i < n-2; i++ {
if 2*nums[i]+2*nums[i+2] == nums[i+1] {
res++
}
}
return res
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/12/22/PS/LeetCode/count-subarrays-of-length-three-with-a-condition/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.