Longest Turbulent Subarray - Problem
Given an integer array arr, return the length of a maximum size turbulent subarray of arr.
A subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray.
More formally, a subarray [arr[i], arr[i + 1], ..., arr[j]] of arr is said to be turbulent if and only if:
- For
i <= k < j:arr[k] > arr[k + 1]whenk - iis even, andarr[k] < arr[k + 1]whenk - iis odd. - OR, for
i <= k < j:arr[k] > arr[k + 1]whenk - iis odd, andarr[k] < arr[k + 1]whenk - iis even.
Input & Output
Example 1 — Basic Turbulent Array
$
Input:
arr = [9,4,2,10,7,8,8,1,9]
›
Output:
5
💡 Note:
The longest turbulent subarray is [4,2,10,7,8] with pattern: 4 > 2 < 10 > 7 < 8, length = 5
Example 2 — All Equal Elements
$
Input:
arr = [4,4,4]
›
Output:
1
💡 Note:
All elements are equal, so no turbulent subarray exists beyond single elements
Example 3 — Two Elements
$
Input:
arr = [100,1]
›
Output:
2
💡 Note:
A subarray of length 2 with different elements is turbulent: 100 > 1
Constraints
- 1 ≤ arr.length ≤ 4 × 104
- 0 ≤ arr[i] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Array with elements to check for turbulent pattern
2
Find Pattern
Look for alternating > and < comparisons
3
Return Length
Length of longest turbulent subarray
Key Takeaway
🎯 Key Insight: Use dynamic programming to track sequences ending with increasing/decreasing patterns for O(n) solution
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code