Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

413. Arithmetic Slices 🌟🌟

An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.

A subarray is a contiguous subsequence of the array.

DP

	array: [1,2,3,4]
	Here first 3 element:   [1,2,3] is arithmetic -> count=1
	also next 3 element:    [2,3,4] is arithmetic -> count=1
	now all together:     [1,2,3,4] is arithmetic -> count=1
class Solution {
public:
    int numberOfArithmeticSlices(vector<int>& nums)
    {
        int n = nums.size();
        if (n < 3)
            return 0;
        vector<int> dp(n, 0);
        int ans = 0;

        for (int i = 2; i < n; ++i) {
            if (nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]) {
                dp[i] = dp[i - 1] + 1;
                ans += dp[i];
            }
        }
        return ans;
    }
};