575. Longest Turbulent Subarray
You are given an integer array arr. A subarray is turbulent when the comparison between every pair of neighbors strictly flips direction as you walk it: up, down, up, down, ... or down, up, down, up, ... Equal neighbors break turbulence — no = is allowed inside the run.
Return the length of the longest turbulent subarray as an integer. A single element is always turbulent, so the answer is at least 1.
Example 1:
Input: arr = [9, 4, 2, 10, 7, 8, 8, 1, 9]
Output: 5
Explanation: The stretch [4, 2, 10, 7, 8] zigzags: 4 > 2 < 10 > 7 < 8. The pair 8, 8 that follows kills the run, and nothing longer exists.
Example 2:
Input: arr = [4, 8, 12, 16]
Output: 2
Explanation: Everything rises, so no direction ever flips. Any two unequal neighbors, like [4, 8], form a turbulent run of length 2.
Example 3:
Input: arr = [100]
Output: 1
Explanation: One element on its own is trivially turbulent.
Constraints:
- 1 ≤ arr.length ≤ 4 * 10⁴
- 0 ≤ arr[i] ≤ 10⁹
Hints:
Encode each neighbor pair as a sign: +1 if it goes up, -1 if it goes down, 0 if equal. Turbulent means consecutive signs are opposite and never 0.
Track two counters while scanning: the length of the longest turbulent run ENDING here whose last step went up, and the same for down. Each new pair extends exactly one of them and resets the other.
Equal neighbors reset both counters to 1 — but the overall answer never drops below what you have already seen (and never below 1).
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: arr = [9, 4, 2, 10, 7, 8, 8, 1, 9]
Expected output: 5