413. Arithmetic Slices

class Solution {
    public int numberOfArithmeticSlices(int[] nums) {
        // dp or math formula
        int ans = 0;
        // cache the number of arithmetic subarrays ends at index i-1;
        int count= 0;
        int preDiff= Integer.MIN_VALUE;
        for(int i=1; i<nums.length; i++){
            int diff = nums[i]-nums[i-1];
            if (diff!=preDiff){
                count=0;
            }else{
                count++;
                ans+=count;
            }
            preDiff = diff;
        }
        return ans;
    }
}

Last updated