Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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;
}
share|improve this question
    
What's the purpose of list? – JS1 Jun 4 '15 at 18:37
    
Right, it is redundant. – marciano Jun 4 '15 at 18:39
    
I've rolled back Rev 2. See What should I do when someone answers my question?. – 200_success Jun 4 '15 at 19:36

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.