Arithmetic Slices LeetCode Solution

Last updated on July 18th, 2024 at 09:47 pm

Here, We see Arithmetic Slices LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Topics

Dynamic Programming, Math

Companies

Baidu

Level of Question

Medium

Arithmetic Slices LeetCode Solution

Arithmetic Slices LeetCode Solution

Problem Statement

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.

  • For example, [1,3,5,7,9][7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences.

Given an integer array nums, return the number of arithmetic subarrays of nums.

subarray is a contiguous subsequence of the array.

Example 1:
Input: nums = [1,2,3,4]
Output: 3
Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.

Example 2:
Input: nums = [1]
Output: 0

1. Arithmetic Slices LeetCode Solution C++

class Solution {
public:
    int numberOfArithmeticSlices(vector<int>& nums) {
    int count=0,ans=0;
    for(int i=2;i<nums.size();i++)  
    {
        if(nums[i]-nums[i-1]==nums[i-1]-nums[i-2]){
            count++;
            ans+=count;}
        else count=0;
    }
    return ans;        
    }
};

2. Arithmetic Slices LeetCode Solution Java

class Solution {
    public int numberOfArithmeticSlices(int[] nums) {
	var slices = 0;
	for (int i = 2, prev = 0; i < nums.length; i++)
		slices += (nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]) 
				? ++prev 
				: (prev = 0);
	return slices;        
    }
}

3. Arithmetic Slices Solution JavaScript

var numberOfArithmeticSlices = function(nums) {
	let sum = 0,
		dp = Array(nums.length).fill(0);
	for (var i = 2; i <= dp.length - 1; i++) {
		if (nums[i] - nums[i - 1] === nums[i - 1] - nums[i - 2]) {
			dp[i] = 1 + dp[i - 1];
			sum += dp[i];
		}
	}
	return sum;    
};

4. Arithmetic Slices Solution Python

class Solution(object):
    def numberOfArithmeticSlices(self, nums):
        le=len(nums)
        l=[0]*(le)
        for i in range(2,le):
            if nums[i]-nums[i-1] == nums[i-1]-nums[i-2]:
                l[i]=1+l[i-1]
        return sum(l)
Scroll to Top