---
# System prepended metadata

title: 2765. Longest Alternating Subarray
tags: [Leetcode, Two Pointers, Easy, Sliding Window]

---

Link: https://leetcode.com/problems/longest-alternating-subarray/description/
## 思路
sliding window里面是alternating subarray 随着sliding window移动 更新答案
如果移动右指针```j```后发现不再是alternating subarray
那么就需要移动左指针```i```如果```nums[j-1]```不能做alternating subarray的开头(```nums[j-1]+1!=nums[j]```) 那么只能尝试用```nums[j]```做开头
## Code
```python=
class Solution:
    def alternatingSubarray(self, nums: List[int]) -> int:
        i, j = 0, 1
        ans = 0
        while j<len(nums):
            if (j-i)%2==0 and nums[j]!=nums[i]:
                if nums[j]-nums[j-1]==1: i = j-1
                else: i=j
            elif (j-i)%2==1 and nums[j]!=nums[i]+1:
                if nums[j]-nums[j-1]==1: i = j-1
                else: i=j
            ans = max(ans, j-i+1)
            j += 1
        return ans if ans>1 else -1
```