SDE & MLE Prep

978. Longest Turbulent Subarray

Problem

A subarray is turbulent if the comparison sign flips between every pair of adjacent elements (bigger, smaller, bigger… or the reverse). Return the length of the longest turbulent subarray of arr.

Example: [9,4,2,10,7,8,8,1,9] → 5 ([4,2,10,7,8])

Constraints: n ≤ 4·10⁴.

Track the length of the turbulent run ending here whose last step goes up and whose last step goes down. An up step extends a run that last went down (and vice versa); an equal pair resets both to 1.

Complexity: O(n) time, O(1) space.

class Solution:
    def maxTurbulenceSize(self, arr: List[int]) -> int:
        best = up = down = 1
        for i in range(1, len(arr)):
            if arr[i] > arr[i - 1]:
                up, down = down + 1, 1
            elif arr[i] < arr[i - 1]:
                up, down = 1, up + 1
            else:
                up = down = 1
            best = max(best, up, down)
        return best