my java solution with time-O(n) space-O(2n)


  • 0
    E
    public int numberOfArithmeticSlices(int[] A) {
            // sanity check
            if (A == null || A.length <= 2) {
                return 0;
            }
            
            // helper[i] represents the number of arithmetic slices
            int[] helper = new int[A.length];
            helper[0] = 0;
            helper[1] = 0;
            // length[i] represents the length of arithmetic slices
            int[] length = new int[A.length];
            length[0] = 1;
            length[1] = 2;
            int sum = 0;
            for (int i = 2; i < A.length; i++) {
                if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) {
                    length[i] = length[i - 1] + 1;
                    if (length[i] >= 3) {
                        helper[i] = 1 + (length[i] - 3);
                        sum += helper[i];
                    } else {
                        helper[i] = 0;
                    }
    
                } else {
                    length[i] = 2;
                    helper[i] = 0;
                }
            }
            return sum;
        }
    

Log in to reply
 

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