mediumDynamic Programming 1DPure DSA~25 min
Count Contiguous Arithmetic Subarrays
Count the number of contiguous subarrays (length >= 3) of a reading series that form an arithmetic progression — equal consecutive differences.
Problem
Given an integer array nums, return the number of arithmetic subarrays. A subarray is arithmetic if it has at least 3 elements and the difference between consecutive elements is constant.
Input
An integer array nums.
Output
An integer: the count of arithmetic subarrays.
Constraints
- 1 <= nums.length <= 5000
- -1000 <= nums[i] <= 1000
- Subarrays must be contiguous and length >= 3.
Examples
Example 1
Input
nums = [1,2,3,4]
Output
3
[1,2,3], [2,3,4], and [1,2,3,4] are arithmetic.
Example 2
Input
nums = [1,3,5,7,9]
Output
6
Several overlapping arithmetic runs contribute 6.