mediumDynamic Programming 1DPure DSA~20 min
Longest Turbulent Subarray
A metric stream is 'turbulent' over a stretch when consecutive comparisons strictly alternate between rising and falling. Find the length of the longest turbulent stretch.
Problem
Given an integer array arr, return the length of the longest turbulent subarray: a subarray where the comparison sign between adjacent elements flips for each adjacent pair (i.e., > then < then > ...), and where any two adjacent elements differ.
Input
An integer array arr.
Output
An integer: the length of the longest turbulent subarray.
Constraints
- 1 <= arr.length <= 40000
- 0 <= arr[i] <= 10^9
Examples
Example 1
Input
arr = [9,4,2,10,7,8,8,1,9]
Output
5
[4,2,10,7,8] alternates < > < > giving length 5.
Example 2
Input
arr = [4,8,12,16]
Output
2
Only adjacent rising pairs; max turbulent length is 2.