> For the complete documentation index, see [llms.txt](https://ucan.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ucan.gitbook.io/notes/dynamic-programming/413.-arithmetic-slices.md).

# 413. Arithmetic Slices

```java
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;
    }
}
```
