Sponsored
Sponsored
In this approach, a sliding window technique is used to identify the longest turbulent subarray. We maintain two pointers: 'start' and 'end'. Initially, 'start' is set to 0, and 'end' is used to iterate over the array. At each step, we check the relationship between consecutive elements to determine the turbulence. When the pattern breaks, we calculate the length of the turbulent segment and adjust the pointers accordingly.
Time Complexity: O(n), where n is the length of the array, as the solution involves a single pass over the array.
Space Complexity: O(1), as it uses a constant amount of extra space.
1var maxTurbulenceSize = function(arr) {
2 let n = arr.length;
3 let max_len = 1, current_len = 1;
4 for (let i = 1; i < n; ++i) {
5 if (arr[i - 1] < arr[i]) {
6 current_len = (i % 2 === 0) ? 2 : 1;
7 } else if (arr[i - 1] > arr[i]) {
8 current_len = (i % 2 === 1) ? 2 : 1;
9 } else {
10 current_len = 1;
11 }
12 max_len = Math.max(max_len, current_len);
13 }
14 return max_len;
15};
The JavaScript implementation follows the same logic as the other languages, iterating through the array and checking for turbulent patterns using conditionals.
This approach utilizes dynamic programming to maintain two arrays: inc
and dec
, which record the lengths of increasing and decreasing turbulent subarrays that end at each index. The solution updates these values based on the conditions of the current element relative to the previous one, and tracks the global maximum using the values in inc
and dec
.
Time Complexity: O(n), as the array is traversed once.
Space Complexity: O(1), minimal additional space is used.
This C implementation uses two variables, inc
and dec
, to manage the lengths of turbulent subarrays. During each iteration, they are updated based on comparisons between current and previous elements.