413. Arithmetic Slices

Arithmetic Slices - LeetCode

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.

A 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

Constraints:

1 <= nums.length <= 5000
-1000 <= nums[i] <= 1000

  • code
# [1,3,5,7,9,9,9] ;  1,3,5;  1,3,5,7; 3,5,7; 3579; 579; 999;
# 13579;  999 6+1 7
# 1 + 2 + 3.. (n-3+1) 
#  (1 + (n - 3 + 1)) * (n-3+1) // 2
# length of consecutive elements -> num of subarrays (n - 1)(n - 2) // 2

# 9999   999, 999 9999
class Solution:
    def numberOfArithmeticSlices(self, nums: List[int]) -> int:
        if len(nums) < 3: return 0
        nums.append(inf)
        diff = nums[1] - nums[0]
        i = 2
        cur_len = 2
        res = 0
        while i < len(nums):
            if nums[i] - nums[i-1] == diff:
                cur_len += 1
            else:
                res += (cur_len - 1) * (cur_len - 2) // 2
                diff = nums[i] - nums[i-1]
                cur_len = 2
            i += 1
        return res