Longest Turbulent Subarray Problem
Description
LeetCode Problem 978.
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] when k is odd, and
- arr[k] < arr[k + 1] when k is even.
- Or, for i <= k < j:
- arr[k] > arr[k + 1] when k is even, and
- arr[k] < arr[k + 1] when k is odd.
Example 1:
Input: arr = [9,4,2,10,7,8,8,1,9]
Output: 5
Explanation: arr[1] > arr[2] < arr[3] > arr[4] < arr[5]
Example 2:
Input: arr = [4,8,12,16]
Output: 2
Example 3:
Input: arr = [100]
Output: 1
Constraints:
- 1 <= arr.length <= 4 * 10^4
- 0 <= arr[i] <= 10^9
Solution
Approach: Track Runs Ending Up and Ending Down
A turbulent subarray is one whose comparisons alternate: up, down, up, ... or down, up, down, .... The two formal cases in the statement (by odd and even k) just say that it can start with either direction.
Walk the array once and keep two lengths for the subarray ending at index i:
up: the longest turbulent subarray ending atiwhose last step goes up (arr[i - 1] < arr[i]),down: the same, with a last step going down.
Compare arr[i] with arr[i - 1]:
- Up step: it can extend a run whose last step went down, so
up = down + 1. A run ending with a down step cannot end here, sodown = 1. - Down step: symmetrically,
down = up + 1andup = 1. - Equal: equal neighbors break any turbulent run, so both become
1(the element alone).
The answer is the largest up or down seen, starting from 1 because a single element is always turbulent.
In case 1, use the old value of down to compute up before resetting down. The updates must use the values from index i - 1.
Example with arr = [9,4,2,10,7,8,8,1,9]: the steps are down, down, up, down, up, equal, down, up. The run 4 > 2 < 10 > 7 < 8 reaches length 5 at index 5, and the equal pair 8, 8 resets it.
Complexity: O(n) time and O(1) space, where n is the length of arr.
class Solution:
def maxTurbulenceSize(self, arr: List[int]) -> int:
# up: longest turbulent subarray ending at i whose last step goes up (arr[i - 1] < arr[i]);
# down: the same with a last step going down. A single element counts as length 1 for both.
up = down = 1
best = 1
for i in range(1, len(arr)):
if arr[i] > arr[i - 1]:
up, down = down + 1, 1 # an up step extends a run whose last step went down
elif arr[i] < arr[i - 1]:
up, down = 1, up + 1
else:
up, down = 1, 1 # equal neighbors break every run
best = max(best, up, down)
return best
Now write it from memory
Close the write-up and solve it yourself against the tests.