Leetcode 1020 Solution

This article provides solution to leetcode question 1020 (longest-turbulent-subarray)

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

Solution

class Solution(object):
    def maxTurbulenceSize(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        if len(A) <= 1:
            return len(A)
        elif len(A) == 2:
            return 2 if A[0] != A[1] else 1

        l = 0
        r = 1
        last_sign = cmp(A[0], A[1])
        ans = 0

        for i in range(2, len(A)):
            sign = cmp(A[i - 1], A[i])

            if sign == 0:
                l = r = i
            elif last_sign == 0:
                l = i - 1
                r = i
            else:
                if sign == last_sign:
                    l = i - 1
                r = i

            last_sign = sign

            ans = max(ans, r - l + 1)

        return ans