LeetCode 413.

Tags:

Complexity

  • Time complexity: O(n^2)

  • Space complexity: O(n^2)

Code

class Solution {
    public int numberOfArithmeticSlices(int[] nums) {
        int n = nums.length;
        boolean[][] isAri = new boolean[n][n];
        for (boolean[] r: isAri) {
            Arrays.fill(r, false);
        }
        int count = 0;

        for (int i=0; i<=n-3; i++) {
            if (nums[i+1]-nums[i] == nums[i+2]-nums[i+1]) {
                isAri[i][i+2] = true;
                count++;
            }
        }

        for (int len=3; len<=n; len++) {
            for (int i=0; i<=n-len; i++) {
                if (isAri[i+1][i+len-1] && 
                    nums[i+1]-nums[i] == nums[i+2]-nums[i+1]) {
                    isAri[i][i+len-1] = true;
                    count++;
                }
            }
        }

        return count;
    }
}

Check out the description of this problem at LC 413.