413. Arithmetic Slices
1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -91, 1, 2, 5, 7A = [1, 2, 3, 4]
return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself.// Dynamic Programming
int numberOfArithmeticSlices(vector<int>& A) { // time: O(n); space: O(n)
if (A.empty()) return 0;
int n = A.size(), res = 0;
vector<int> dp(n, 0); // the number of arithmetic slices ending with 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;
res += dp[i];
}
}
return res;
}Last updated