[LeetCode] Arithmetic Slices

413. Arithmetic Slices

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 class Solution {
public:
int numberOfArithmeticSlices(vector<int>& nums) {
if(nums.size() <= 2) return 0;
int res = 0, cnt = 0;
for(int i = 2; i < nums.size(); i++) {
if(nums[i] + nums[i-2] == 2 * nums[i-1]) cnt++;
else {
res += cnt * (cnt + 1) / 2;
cnt = 0;
}
}
return res + cnt * (cnt + 1) / 2;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/10/PS/LeetCode/arithmetic-slices/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.