Skip to main content

413. Arithmetic Slices

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

Python

  • 4個元素的等差數列,可能組合為:
(43+1)+(44+1)=3(4-3+1)+(4-4+1) = 3
  • 5個元素的等差數列,可能組合為:
(53+1)+(54+1)+(55+1)=6(5-3+1)+(5-4+1)+(5-5+1) = 6
  • n個元素的等差數列,可能的組合為:
i=1n+1n\displaystyle\sum_{i=1}^{n+1} n
class Solution:
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
if len(nums) < 3:
return 0

arith_length = 0
counter = 0

for i in range(len(nums)-2):
if nums[i+2] - nums[i+1] == nums[i+1] - nums[i]:
arith_length += 1
counter += arith_length
else:
arith_length = 0

return counter