[C] 10 lines simple solution


  • 0
    P

    Iterate over array with n elements once. Time complexity equals O(n).

    int numberOfArithmeticSlices(int* A, int ASize) {
        int i, j, diff, offset, count = 0;
    
        for (i=0;i<ASize-1;i=j) {
            diff = A[i]-A[i+1];
            j = i+1;
            while (j<ASize-1 && A[j]-A[j+1]==diff)
                j++;
    
            offset = j-i;
            if (offset-->=2)
                count += (offset*(offset+1))>>1;
        }
    
        return count;
    }
    

Log in to reply
 

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