# 978. Longest Turbulent Subarray
The problem asks us to find the longest turbulent subarray, so the sliding window method is the first thought I have. So we slide the window through the array to find the longest subarray that is a turbulent array.
So each index left of the array, we find the longest turbulent array that starts at index left, and ends at index right. And than we start another search at index right.
Question Link is here.
class Solution:
def maxTurbulenceSize(self, arr) -> int:
ans = 1
if len(arr) <= 1:
return len(arr)
i = 0
while i < len(arr) - 1:
currSign = 0
if arr[i] > arr[i+1]:
currSign = 1
elif arr[i] < arr[i+1]:
currSign = -1
if currSign == 0:
i += 1
continue
right = i + 1
while right < len(arr):
nextSign = 0
if arr[right] > arr[right - 1]:
nextSign = 1
elif arr[right] < arr[right - 1]:
nextSign = -1
if nextSign == currSign * -1:
currSign *= -1
right += 1
else:
break
ans = max(ans, right - i)
i = right - 1
return ans
This solution has Time Complexity of , and space complexity of .