3 elements forms arithmetic sequence, when difference between any two consecutives of them is the same.
In our task we are given array A. Any pair of integers in this array is called slice (eg. (B,C)), when 0 <= B < C< N, where N is an array length (0<=N<=60).
A slice (B,C) is called arithmetic, when the sequence: A[B],A[B+1],...,A[C-1],A[C] is arithmetic and B+1 < C.
My method should return the number of arithmetic slices in array. Time complexity should be linear. When result exceeds 1000000000 method should return -1. Is my solution correct?
public int computeNumberOfArithmeticSlices(int[] A) {
int front = 0, total = 0;
int result = 0;
List list;
for (int back = 0; back < A.length && front < A.length; ) {
list = new ArrayList();
front = back + 2;
total = A[front - 1] - A[back];
list.add(back);
list.add(front - 1);
int i = 0;
boolean ok = false;
while (front < A.length && A[front] - A[front - 1] == total) {
ok = true;
i++;
list.add(front);
back = front;
front++;
result += i;
if (result > 1000000000)
return -1;
}
if (!ok)
back++;
}
return result;
}
list
? – JS1 Jun 4 '15 at 18:37