Skip to content

Instantly share code, notes, and snippets.

@hcn1519
Created September 25, 2022 22:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hcn1519/2f3c0408b03a9a42b713212d8de54704 to your computer and use it in GitHub Desktop.
Save hcn1519/2f3c0408b03a9a42b713212d8de54704 to your computer and use it in GitHub Desktop.
class Solution:
# sliding window(O(n))
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
def numberOfArithmeticArr(n: int) -> int:
if n < 3:
return 0
return ((n - 2) * (n - 1)) // 2
if len(nums) < 3:
return 0
startIdx = 0
endIdx = 1
diff = nums[startIdx] - nums[endIdx]
result = 0
for i in range(2, len(nums)):
diff2 = nums[endIdx] - nums[i]
if diff != diff2:
# end of arithmetic slice
if endIdx - startIdx > 1:
result += numberOfArithmeticArr(n = endIdx - startIdx + 1)
startIdx = endIdx
endIdx = i
diff = nums[startIdx] - nums[endIdx]
else:
endIdx = i
if endIdx - startIdx > 1:
result += numberOfArithmeticArr(n = endIdx - startIdx + 1)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment