# Java 2ms AC solution

• The heart part of this question is `(n-1)*(n-2)/2`. And the rest is easy. See the note in the code.

Looks long, but simple actually.

``````public class Solution {
private int res = 0;
public int numberOfArithmeticSlices(int[] A) {
// for n consecutive arithmetic number, the number of slices: (n-1)*(n-2)/2
int len = A.length;
if (len <= 2) return 0;
int[] count = new int[len];
int from = 2;
// This while block can be write out side of the numberOfArithmeticSlices() function, for example , write a new function startIndex().
while (from < len) {
if (A[from] - A[from - 1] == A[from - 1] - A[from - 2]) { count[from] = 3; break; }
from++;
if (from == len) return 0;
}
int i = from + 1;

while (i < len) {
int cur = A[i] - A[i - 1], pre= A[i - 1] - A[i - 2];
if (cur == pre) {
count[i] = count[i - 1] + 1;
count[i - 1] = 0;
i++;
} else if (cur != pre && i < len - 2) {
from = i + 2;
// This is also the function startIndex().
while (from < len) {
if (A[from] - A[from - 1] == A[from - 1] - A[from - 2]) {
count[from] = 3; break;
}
from++;
}
i = from + 1;
}
}
for (int k = 0; k < count.length; k++) {
if (count[k] != 0) res += (count[k]-1)*(count[k]-2)/2;
}
return res;
}
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.