Problem Description
Given an integer array arr, find the length of the longest turbulent subarray. A subarray is turbulent if the comparison sign between every two consecutive elements alternates. For example, in a turbulent subarray, if arr[i] > arr[i+1] then arr[i+1] < arr[i+2] must hold, or vice versa.
Key Insights
- A turbulent subarray requires alternating "greater than" and "less than" comparisons.
- A sliding window or dynamic programming approach can be used to solve the problem in O(n) time.
- Reset the subarray length when encountering equal adjacent elements or when the alternating condition fails.
- Handle the case where the array has only one element.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Solution
We can solve the problem using a dynamic programming / sliding window approach:
- If the array has only one element, return 1.
- Initialize a variable (currentLength) to keep track of the current turbulent subarray length.
- Traverse the array from the second element and:
- If the current element is equal to the previous element, reset currentLength to 1.
- Otherwise, if the current and previous comparisons create a valid alternating pattern when compared to the one before them, increment currentLength.
- If the alternating pattern breaks, reset currentLength to 2 (since the current two elements may start a new turbulent subarray).
- Track the maximum length seen during the traversal.
Key trick: Instead of precomputing comparison signs, we check the alternating condition on the fly using the relationship between three consecutive elements.