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.
1public class 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}
C#'s implementation leverages familiar syntax found in Java or C++. It traverses the array, computing turbulent lengths and updating the result 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
This Python function employs dynamic programming logic to evaluate the turbulent pattern. Two variables, inc
and dec
, capture subarray lengths, updated dynamically on each iteration.