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;
}
1 Answer 1
Using raw types (generic types without type parameter) is a major violation:
List list = new ArrayList();
Never ever do this. In any case, as @JS1 already pointed out in comments, this list in your implementation is unused anyway. (another major violation)
Declare variables in the smallest scope possible.
For example,
you could declare front
inside the for
statement,
and total
inside the body:
for (int back = 0, front = 0; back < A.length && front < A.length; ) {
front = back + 2;
int total = A[front - 1] - A[back];
You could also convert the inner while
loop to a for
loop,
and declare the variable i
inside the statement.
list
? \$\endgroup\$