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.
Input: nums =[1,2,1,4,1]Output: 1Explanation:
Only the subarray `[1,4,1]` contains exactly 3 elements where the sum of the
first and third numbers equals half the middle number.
Example 2:
1
2
3
4
5
Input: nums =[1,1,1]Output: 0Explanation:
`[1,1,1]`is the only subarray of length 3. However, its first and third
numbers do not add to half the middle number.
classSolution {
publicintcountSubarrays(int[] nums) {
int ans = 0;
for (int i = 1; i < nums.length- 1; i++) {
if (nums[i - 1]+ nums[i + 1]== nums[i]/ 2.0) {
ans++;
}
}
return ans;
}
}
1
2
3
4
5
6
7
classSolution:
defcountSubarrays(self, nums: List[int]) -> int:
ans: int =0for i in range(1, len(nums) -1):
if nums[i -1] + nums[i +1] == nums[i] /2:
ans +=1return ans