117. Longest Turbulent Subarray

Medium · Array

A turbulent subarray is one where consecutive elements strictly alternate between being greater than and less than each other. For example, in [9,4,2,10,7], we have 9>4, 4>2, 2<10, 10>7 — alternating between > and <. Your task is to find the length of the longest contiguous subarray that exhibits this turbulent pattern. Input: an array of integers. Return: the length of the longest turbulent subarray (minimum length is 1, since any single element is trivially turbulent).

Examples

Example 1
Input: [9, 4, 2, 10, 7, 8, 8, 1, 9]
Output: 5
Explanation: [4,2,10,7,8] alternates < > < > and has length 5
Example 2
Input: [4, 8, 12, 16]
Output: 2
Explanation: No alternation; any two adjacent distinct elements is length 2

Constraints