Ref: https://leetcode-cn.com/problems/longest-turbulent-subarray/
這道題使用滑動(dòng)窗口解決(和
為左右邊界指針)旱捧,主要難點(diǎn)在邊界條件。大致思路如下:
- 如果
且
,則
曹阔;
- 如果
且
株憾,則
筷黔;
- 除此之外草巡,還需注意
的情況唯卖,在這種情況下憎夷,只需在
與
相等時(shí)莽鸿,
,而始終要進(jìn)行
拾给。
主要代碼如下:
class Solution:
def maxTurbulenceSize(self, arr: List[int]) -> int:
l = len(arr)
if l == 0:
return 0
result = 1
left = 0
right = 0
while right < l - 1:
if left == right:
if arr[right] == arr[right + 1]:
left += 1
right += 1
else:
if arr[right - 1] > arr[right] and arr[right] < arr[right + 1]:
right += 1
elif arr[right - 1] < arr[right] and arr[right] > arr[right + 1]:
right += 1
else:
left = right
result = max(result, right - left + 1)
return result