978. Longest Turbulent Subarray

2021-02-08  本文已影响0人  morningstarwang

Ref: https://leetcode-cn.com/problems/longest-turbulent-subarray/

这道题使用滑动窗口解决(leftright为左右边界指针),主要难点在边界条件。大致思路如下:

主要代码如下:

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
上一篇下一篇

猜你喜欢

热点阅读