Q56 Arithmetic Slices - LeetCode 413

PHOTO EMBED

Sat Apr 01 2023 13:00:08 GMT+0000 (Coordinated Universal Time)

Saved by @Ayush_dabas07

class Solution {
    public int numberOfArithmeticSlices(int[] nums) {
        /* Q56 of dp playlist , every cell denotes no. of subarrays of dp which
        ends in ith element , our answer will be total sum of all such subarrays
        stored in dp
        */

        //making dp
        int n = nums.length;

        if( n < 3) return 0;    //we need >= 3 elements for an AP

        int[] dp = new int[n];

        //we skip the first 2 elements 
        int ans = 0 ;
        for(int i = 2 ; i < n ; i++){
            int val1 = nums[i] - nums[i-1];
            int val2 = nums[i-1] - nums[i-2];
            
            /*we check if the common difference is same ith element will have 
            +1 ap than the previous element
            */
            if(val1 == val2)
            dp[i] = dp[i-1] +1;

            else
            dp[i] = 0;
            
            //answer will be sum of all 
            ans += dp[i];
        }

        return ans;
    }
}
content_copyCOPY

https://leetcode.com/problems/arithmetic-slices/