Created
December 10, 2023 22:14
-
-
Save primaryobjects/22b54d6885faf5697cbe798df4980709 to your computer and use it in GitHub Desktop.
Longest Turbulent Subarray https://leetcode.com/problems/longest-turbulent-subarray/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def maxTurbulenceSize(self, arr: List[int]) -> int: | |
# O(n) | |
max_length = 1 | |
is_greater = None | |
cur_length = 1 | |
for i in range(len(arr) - 1): | |
# Compare the current and next array values. | |
s0 = arr[i] | |
s1 = arr[i+1] | |
# Initialize condition or flip it. | |
is_greater = (not is_greater) if is_greater != None else s0 > s1 | |
if (is_greater and s0 > s1) or (not is_greater and s0 < s1): | |
cur_length += 1 | |
else: | |
# Not valid. Check if we've found a longest subarray up to this point. | |
max_length = max(cur_length, max_length) | |
cur_length = 2 if s0 != s1 else 1 | |
is_greater = not is_greater | |
return max(cur_length, max_length) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
978. Longest Turbulent Subarray | |
Solved | |
Medium | |
Topics | |
Companies | |
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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment