Question 413. Arithmetic Slices

Link:

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

My code:

class Solution:
    def numberOfArithmeticSlices(self, A: List[int]) -> int:
        if len(A)<3:
            return 0
        else:
            #Here the dynamic programming we use here dp[i] is the number of arithmetic list end up with ith element
            ArSeqList = [0,0]
            for i in range(2,len(A)):
                if A[i]-A[i-1] == A[i-1]-A[i-2]:
                    Num = ArSeqList[i-1] +1
                    ArSeqList.append(Num)
                else:
                    ArSeqList.append(0)
            return sum(ArSeqList)

The idea of the code:

The recursion follows the idea like this: the ith of the storage list is the number of the arithmetic sequence end up with ith element in the original list. Given the number of the ith element, the number of (i+1)the element is determined by following logic: we check if the difference between ith element and i-1 th element and i-1 and i-2 the element. If they are the same, then we know that for any arithmetic sequence end up with i-1th element, we put ith elment in the list it is also arithmetic as it is tested by the previous test. So the total number is the number of the arithmetic sequence end up with i-1th elment +1. If the difference are not the same, them there is no arithmetic sequence end up with ith element as if there is one, it must include at least three elements, however, the first possible choice if denied by this test. Hence with this recursion, we may figure out all the am sequence end up with ith element in the original list, the to get the total result, we just need to sum all the numbers in the result list.

Leave a comment