• Time:O(n)
• Space:O(n)

## C++

``````class Solution {
public:
int numberOfArithmeticSlices(vector<int>& A) {
const int n = A.size();
if (n < 3)
return 0;

vector<int> dp(n);  // # arithmetic slices ends at i

for (int i = 2; i < A.size(); ++i)
if (A[i] - A[i - 1] == A[i - 1] - A[i - 2])
dp[i] = dp[i - 1] + 1;

return accumulate(begin(dp), end(dp), 0);
}
};
``````

## JAVA

``````class Solution {
public int numberOfArithmeticSlices(int[] A) {
final int n = A.length;
if (n < 3)
return 0;

int[] dp = new int[n]; // dp[i] := # of arithmetic slices ends at A[i]

for (int i = 2; i < n; ++i)
if (A[i] - A[i - 1] == A[i - 1] - A[i - 2])
dp[i] += dp[i - 1] + 1;

return Arrays.stream(dp).sum();
}
}
``````

• Time:O(n)
• Space:O(1)

## C++

``````class Solution {
public:
int numberOfArithmeticSlices(vector<int>& A) {
int ans = 0;
int dp = 0;  // # arithmetic slices ends at i

for (int i = 2; i < A.size(); ++i)
if (A[i] - A[i - 1] == A[i - 1] - A[i - 2])
ans += ++dp;
else
dp = 0;

return ans;
}
};
``````

## JAVA

``````class Solution {
public int numberOfArithmeticSlices(int[] A) {
int ans = 0;
int dp = 0;

for (int i = 2; i < A.length; ++i) {
if (A[i] - A[i - 1] == A[i - 1] - A[i - 2])
ans += ++dp;
else
dp = 0;
}

return ans;
}
}
``````

## Python

``````class Solution:
def numberOfArithmeticSlices(self, A: List[int]) -> int:
ans = 0
dp = 0

for i in range(2, len(A)):
if A[i] - A[i - 1] == A[i - 1] - A[i - 2]:
dp += 1
ans += dp
else:
dp = 0

return ans
``````