Accepted one pass,3ms, java solution


  • 0
    F
    public int numberOfArithmeticSlices(int[] A) {
        
            int result=0;
            int len=1;
            int diff=Integer.MIN_VALUE;
            for(int i=0;i<A.length-1;i++){
                if(A[i]-A[i+1]==diff){
                    len+=1;
                }
                else{
                    if(len>=2){
                        result+=getCombo(len+1);
                    }
                    len=1;
                    diff=A[i]-A[i+1];
                }
            } 
            if(len>=2)
                result+=getCombo(len+1);
            return result;
            
        }
        public int getCombo(int len){
            int count=0;
            int result=1;
            while(len-->=3){
                count=count+(result);
                result+=1;
            }
            return count;
        }
    

    The getCombo function just returns the number of consecutive combinations we could make with the current length. Example, with length 4, we could make 2 combinations with len 3 + 1 combination with len 4.


Log in to reply
 

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