LeetCode 978: Longest Turbulent Subarray Solution
Master LeetCode problem 978 (Longest Turbulent Subarray), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
978. Longest Turbulent Subarray
Problem Explanation
Explanation
To solve this problem, we can iterate through the array and keep track of the current turbulent subarray's length. We will maintain two variables: up to track the length of the current increasing subarray ending at the current index, and down to track the length of the current decreasing subarray ending at the current index. We will update these variables based on the comparison of the current element with the previous one.
At each step, we update the length of the turbulent subarray by taking the maximum of up and down and then reset the appropriate variable based on the comparison of the current element with the previous one.
Finally, we return the maximum turbulent subarray length found during the iteration.
Time complexity: O(n) where n is the number of elements in the input array. Space complexity: O(1)
Solution Code
class Solution {
public int maxTurbulenceSize(int[] arr) {
int n = arr.length;
int up = 1, down = 1, maxLen = 1;
for (int i = 1; i < n; i++) {
if (arr[i - 1] < arr[i]) {
down = up + 1;
up = 1;
} else if (arr[i - 1] > arr[i]) {
up = down + 1;
down = 1;
} else {
up = 1;
down = 1;
}
maxLen = Math.max(maxLen, Math.max(up, down));
}
return maxLen;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 978 (Longest Turbulent Subarray)?
This page provides optimized solutions for LeetCode problem 978 (Longest Turbulent Subarray) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 978 (Longest Turbulent Subarray)?
The time complexity for LeetCode 978 (Longest Turbulent Subarray) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 978 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 978 in Java, C++, or Python.