An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
For example, [1, 3, 5, 7, 9], [7, 7, 7, 7] and [3, -1, -5, -9] are arithmetic sequences.
Given an integer array nums, return the number of arithmetic subarrays of nums.
A subarray is a contiguous subsequence of the array.
Function Signature
def count_arithmetic_subarrays(nums: list[int]) -> int:
Rules
-
Subarrays are counted by position. Two subarrays that hold the same values at different positions count separately.
-
A subarray needs at least three elements to count.
Constraints
-
1 <= len(nums) <= 5000
-
-1000 <= nums[i] <= 1000
Examples
Input: nums = [1, 2, 3, 4]
Output: 3
The arithmetic subarrays are [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4], for a total of 3.
Input: nums = [1]
Output: 0
No subarray has at least three elements, so the answer is 0.
Input: nums = [1, 3, 5, 6, 7, 8]
Output: 4
[1, 3, 5] has difference 2, and [5, 6, 7], [6, 7, 8] and [5, 6, 7, 8] have difference 1. [3, 5, 6] does not count because its differences are 2 and 1.