Java 2ms Simple solution

  • 0

    find all the longest subarrays which is arithmetic, sum up all the sub slices.
    For a arithmetic subarray of length n, there are (n-1)(n-2)/2 arithmetic slices that can be constructed from it.

     public int numberOfArithmeticSlices(int[] A) {
            if(A==null||A.length<3) return 0;
            int left=0, right=2;
            int count=0;
                while(right<A.length&&A[right]-A[right-1]==A[right-1]-A[right-2]) right++;
                if(right-left>=3) count+=(right-left-1)*(right-left-2)/2;
            return count;

Log in to reply

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