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.
1class Solution {
2 public int maxTurbulenceSize(int[] arr) {
3 int n = arr.length;
4 int max_len = 1, current_len = 1;
5 for (int i = 1; i < n; ++i) {
6 if (arr[i - 1] < arr[i]) {
7 current_len = (i % 2 == 0) ? 2 : 1;
8 } else if (arr[i - 1] > arr[i]) {
9 current_len = (i % 2 == 1) ? 2 : 1;
10 } else {
11 current_len = 1;
12 }
13 max_len = Math.max(max_len, current_len);
14 }
15 return max_len;
16 }
17}
The Java solution goes through the array while maintaining the max length using Java's Math.max
to keep the code concise. It checks each element pair for the turbulent pattern and adjusts the lengths accordingly.
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.
1
Utilizing dynamic programming principles, this JavaScript function calculates the maximum length of a turbulent subarray efficiently by maintaining two counters toggled based on current array comparisons.