Problem description:

A sequence of number 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, these are arithmetic sequence:

1
2
3
1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9

The following sequence is not arithmetic.

1
1, 1, 2, 5, 7

A zero-indexed array A consisting of N numbers is given. A slice of that array is any pair of integers (P, Q) such that 0 <= P < Q < N.

A slice (P, Q) of array A is called arithmetic if the sequence:
A[P], A[p + 1], …, A[Q - 1], A[Q] is arithmetic. In particular, this means that P + 1 < Q.

The function should return the number of arithmetic slices in the array A.

Example:

1
2
3
A = [1, 2, 3, 4]

return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself.

solution1:

use 1D dp array. When we have a arithmetic slice in 1…i, which can create total X arithmetic slice, and we got the i+1 element with same distance(slice) as before, the i+1 element can create additional X+1 arithmetic slice. And the sum of arithmetic slices create by sequence 1…i+1 elements would be X+(X+1).
For example:

1
2
3
      1,3,5,7,9,15,20,25,28,29
dp 0 0 1 2 3 0 0 1 0 0
sum 1 3 6 6 6 7 7 7

In the above example, [1,3,5] can make the first slice.
When we add 7 into the sequence, it creates [3,5,7] and [1,3,5,7] slices.
Therefore, total slices when we consider sequence [1,3,5,7] would be
[1,3,5]: which is created and stored in dp[2]
[3,5,7], [1,3,5,7]: in dp[3]
Total: 3 slices

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int numberOfArithmeticSlices(vector<int>& A) {
vector<int> dp(A.size(), 0);
int sum = 0;
for (int i = 2; i < dp.size(); i++) {
if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) {
dp[i] = 1 + dp[i - 1];
sum += dp[i];
}
}
return sum;
}
};

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

solution2:
Since if we don’t have consecutive sequence, we don’t need the dp. We can use a integer to store the slices created by previous consecutive sequence. When the consecutive sequence end, A[i]-A[i-1] != A[i-1]-A[i-2], just reset the counter to zero.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int numberOfArithmeticSlices(vector<int>& A) {
int dp= 0;
int sum = 0;
for (int i = 2; i < A.size(); i++) {
if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) {
dp+=1;
sum += dp;
}
else
dp = 0;
}
return sum;
}
};

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