Simple one pass C++ solution that is easy to follow


  • 0
    G
    class Solution {
    public:
    
        int numberOfArithmeticSlices(vector<int>& A) 
        {
            int Diff = INT_MIN;
            int NumOfSeq = 0;
            int CurrSeqSize = 0;
            
            for(int i = 1; i < A.size(); ++i)
            {
                if(A[i] - A[i - 1] == Diff)
                {
                    CurrSeqSize++;
                    
                    if(CurrSeqSize >= 3)
                    {
                        NumOfSeq++;
                        
                        if(CurrSeqSize > 3)
                        {
                            NumOfSeq += CurrSeqSize - 3;
                        }
                    }
                    
                }
                else
                {
                    Diff = A[i] - A[i - 1];
                    CurrSeqSize = 2;
                }
            }   
            return NumOfSeq;
        }  
    };
    

Log in to reply
 

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