Created
September 25, 2022 22:14
-
-
Save hcn1519/2f3c0408b03a9a42b713212d8de54704 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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