C++ 4-line 3ms solution


  • 0
    A
    int numberOfArithmeticSlices(vector<int>& A) {
        int r = 0;
        for (int i = 2, t = 0; i < A.size(); ++i)
            r += (t = -!((A[i] - A[i-1]) - (A[i-1] - A[i-2])) & (t + 1));
        return r;
    }
    

    Alternatively it can be

    int numberOfArithmeticSlices(vector<int>& A) {
        int r = 0;
        for (int i = 2, t = 0; i < A.size(); ++i)
            r += (t = (A[i] - A[i-1]) == (A[i-1] - A[i-2]) ? t + 1 : 0);
        return r;
    }
    

    The two solutions above are identical. The idea behind it is the same to the other popular DP solutions, like this one, but without using an extra vector.


Log in to reply
 

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