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 ofnums.
A subarray is a contiguous subsequence of the array.
The key idea is that if three consecutive numbers form an arithmetic sequence, then any extension of this sequence by one element (with the same difference) also forms an arithmetic slice. We can use dynamic programming to count the number of arithmetic slices ending at each index.
classSolution {
public:int numberOfArithmeticSlices(vector<int>& nums) {
int n = nums.size(), ans =0, dp =0;
for (int i =2; i < n; ++i) {
if (nums[i] - nums[i-1] == nums[i-1] - nums[i-2]) {
dp +=1;
ans += dp;
} else {
dp =0;
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
funcnumberOfArithmeticSlices(nums []int) int {
n, ans, dp:= len(nums), 0, 0fori:=2; i < n; i++ {
ifnums[i]-nums[i-1] ==nums[i-1]-nums[i-2] {
dp++ans+=dp } else {
dp = 0 }
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
publicintnumberOfArithmeticSlices(int[] nums) {
int n = nums.length, ans = 0, dp = 0;
for (int i = 2; i < n; i++) {
if (nums[i]- nums[i-1]== nums[i-1]- nums[i-2]) {
dp++;
ans += dp;
} else {
dp = 0;
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funnumberOfArithmeticSlices(nums: IntArray): Int {
var ans = 0var dp = 0for (i in2 until nums.size) {
if (nums[i] - nums[i-1] == nums[i-1] - nums[i-2]) {
dp +=1 ans += dp
} else {
dp = 0 }
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defnumberOfArithmeticSlices(self, nums: list[int]) -> int:
n: int = len(nums)
ans: int =0 dp: int =0for i in range(2, n):
if nums[i] - nums[i-1] == nums[i-1] - nums[i-2]:
dp +=1 ans += dp
else:
dp =0return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfnnumber_of_arithmetic_slices(nums: Vec<i32>) -> i32 {
let n = nums.len();
letmut ans =0;
letmut dp =0;
for i in2..n {
if nums[i] - nums[i-1] == nums[i-1] - nums[i-2] {
dp +=1;
ans += dp;
} else {
dp =0;
}
}
ans
}
}