An array of medium-range difference between the number of sub-increments
413. Arithmetic Slices (Medium)
A = [0, 1, 2, 3, 4]
return: 6, for 3 arithmetic slices in A:
[0, 1, 2],
[1, 2, 3],
[0, 1, 2, 3],
[0, 1, 2, 3, 4],
[ 1, 2, 3, 4],
[2, 3, 4]
Subject description:
Given an array, the number of seek medium subinterval difference array is incremented.
Analysis of ideas:
Dynamic programming, with dp [i] represented by A [i] how much incremental arithmetic section at the end of the array there. When A [i] - A [i-1] == A [i-1] - A [i-2], then [A [i-2], A [i-1], A [i]] configuration a sub-interval arithmetic increments. But also to A [i-1] is incremented past the end of a subinterval plus A [i], may be formed as a new sub-interval is incremented.
综上,在 A[i] - A[i-1] == A[i-1] - A[i-2] 时,dp[i] = dp[i-1] + 1。
Because incremental sub-intervals are not necessarily the most is the end of an element can be any element to the end, it is necessary to return the result dp array cumulative.
Code:
public int numberOfArithmeticSlices(int []A){
if(A==null||A.length==0)
return 0;
int []dp=new int [A.length];
for(int i=2;i<A.length;i++){
if(A[i]-A[i-1]==A[i-1]-A[i-2]){
dp[i]=dp[i-1]+1;
}
}
int res=0;
for(int cnt:dp)
res=res+cnt;
return res;
}