Longest Turbulent Subarray

Medium

Description

A turbulent subarray has comparison signs alternating (a[i] < a[i+1] > a[i+2] < ... or a[i] > a[i+1] < a[i+2] > ...). Return the length of the longest one.

Examples

Input:arr = [9,4,2,10,7,8,8,1,9]
Output:5
Explanation:

[4,2,10,7,8] is turbulent.

Input:arr = [1]
Output:1
Explanation:

Edge case with a single-element array.

Input:arr = [2,2,2,5,1,3,1]
Output:4
Explanation:

The array starts with equal elements [2,2,2] which cannot form a turbulent subarray. The longest turbulent subarray is [5,1,3,1] where 5>1<3>1, creating the alternating pattern the requirement is.

Constraints

  • 1 ≤ arr.length ≤ 4 * 10⁴

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!