One pass Concise C++ Solution


  • 1
    class Solution {
    public:
        int numberOfArithmeticSlices(vector<int>& A) {
            int res = 0, start = 0, dis = INT_MAX;
            for (int i = 1; i <= A.size(); i++) {
                if (i == A.size() || A[i] - A[i - 1] != dis) {
                    if (i - start > 2) 
                        res += (i - start - 1) * (i - start - 2) / 2;
                    start = i - 1;
                    if (i < A.size()) dis = A[i] - A[i - 1];
                }
            }
            return res;
        }
    };
    
    

  • 0
    S

    @zyoppy008 buddy, you are so amazing!!! love you!


  • 0
    S

    Can you explain why your algorithm works?


Log in to reply
 

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