A sequence of number is called arithmetic if it consists of in least three elements and if the difference between any Consecutive elements is the same.
For example, these is arithmetic sequence:
1, 3, 5, 7, 97, 7, 7, 73,-1,-5, 9
The following sequence is not arithmetic.
1, 1, 2, 5, 7
A zero-indexed array a consisting of N numbers is given. A slice of that array was 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:
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.
This question let us calculate a kind of arithmetic slice, plainly is to find arithmetic progression, limit the length of the arithmetic progression is at least 3, then [1,2,3,4] contains 3 length of at least 3 of the arithmetic slices, we see [1,2,3,4,5] how many: len = 3: [Three-way], [2,3,4] , [3,4,5]len = 4: [1,2,3,4], [2,3,4,5]len = 5: [1,2,3,4,5] then we can find a recursive type of n arithmetic progression with a length of at least 3 of the number of arithmetic slices (n-1) (n-2)/ 2, then the title becomes the original array to find the length of the arithmetic progression, and then into the formula to calculate the number can be
class Solution {
public:
int numberOfArithmeticSlices(vector<int>& A) {
int = 0 len = 2 n = A size
for (int i = 2; i < n; ++i) {
if (A[I] -A[I- 1] ==A[I- 1] -A[I- 2]) {
++len;
} else {
if ( len > 2 ) res += ( len - 1 ) * ( len - 2 ) * 0.5 ;
len = 2;
}
}
if ( len > 2 ) res += ( len - 1 ) * ( len - 2 ) * 0.5 ;
return res;
}
};
public int NumberOfArithmeticSlices(int[] A)
{
int n = A.Length;
if (n < 3) return 0;
int[] dp = new int[n];
int result = 0;
for ( int i = 2 I < n ++ i ) {
if ( a [ i " - A Span class= "pun" >[ i - 1 ] == A [ i - 1 ] - A [ i - 2
{
dp[i] = dp[i - 1] + 1;
}
result += dp[i];
}
return result;
}
From for notes (Wiz)
413. Array slicing arithmetic Slices