Horje
Find the Longest Turbulent Subarray

Given an integer array arr[] of size n. A subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray. The task is to find the length of a maximum size turbulent subarray of arr[]. 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:

Input: arr = [9,4,2,10,7,8,8,1,9]
Output: 5
Explanation: arr[1] > arr[2] < arr[3] > arr[4] < arr[5]

Input: arr = [4,8,12,16]
Output: 2

Approach:

To solve this problem, we can use a sliding window approach. We maintain two pointers that define the current subarray. As we iterate through the array, we check if the current element continues the turbulent property with the previous element. If it does, we extend the window. If it does not, we reset the window. We keep track of the maximum length of such subarrays during this process.

Steps-by-step approach:

  • Initialize two pointers, start and end, both pointing to the beginning of the array.
  • Iterate through the array using the end pointer.
    • Check if the current subarray maintains the turbulent condition.
      • If it does, update the maximum length.
      • If it does not, move the start pointer to the next position and continue.
  • Return the maximum length of turbulent subarrays found.

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

int maxTurbulenceSize(vector<int>& arr) {
    int n = arr.size();
    if (n < 2) return n;

    int maxLen = 1;
    int start = 0;
    
    for (int end = 1; end < n; ++end) {
        int cmp = arr[end - 1] == arr[end] ? 0 : (arr[end - 1] < arr[end] ? 1 : -1);
        
        if (end == n - 1 || cmp * (arr[end] == arr[end + 1] ? 0 : (arr[end] < arr[end + 1] ? 1 : -1)) != -1) {
            if (cmp != 0) {
                maxLen = max(maxLen, end - start + 1);
            }
            start = end;
        }
    }
    
    return maxLen;
}

int main() {
    // Example 1
    vector<int> arr1 = {9, 4, 2, 10, 7, 8, 8, 1, 9};
    cout << maxTurbulenceSize(arr1) << endl; // Output: 5
    

    return 0;
}
Java
//code by flutterfly
public class TurbulenceSize {
    public static int maxTurbulenceSize(int[] arr) {
        int n = arr.length;
        if (n < 2) return n;

        int maxLen = 1;
        int start = 0;

        for (int end = 1; end < n; ++end) {
            int cmp;
            if (arr[end - 1] == arr[end]) {
                cmp = 0;
            } else if (arr[end - 1] < arr[end]) {
                cmp = 1;
            } else {
                cmp = -1;
            }
            
            int nextCmp = 0;
            if (end < n - 1) {
                if (arr[end] == arr[end + 1]) {
                    nextCmp = 0;
                } else if (arr[end] < arr[end + 1]) {
                    nextCmp = 1;
                } else {
                    nextCmp = -1;
                }
            }

            if (end == n - 1 || cmp * nextCmp != -1) {
                if (cmp != 0) {
                    maxLen = Math.max(maxLen, end - start + 1);
                }
                start = end;
            }
        }

        return maxLen;
    }

    public static void main(String[] args) {
        // Example 1
        int[] arr1 = {9, 4, 2, 10, 7, 8, 8, 1, 9};
        System.out.println(maxTurbulenceSize(arr1)); // Output: 5
    }
}
Python
# code by flutterfly
def max_turbulence_size(arr):
    n = len(arr)
    if n < 2:
        return n

    max_len = 1
    start = 0
    
    for end in range(1, n):
        if arr[end - 1] == arr[end]:
            cmp = 0
        elif arr[end - 1] < arr[end]:
            cmp = 1
        else:
            cmp = -1
        
        if end == n - 1 or cmp * (0 if arr[end] == arr[end + 1] else (1 if arr[end] < arr[end + 1] else -1)) != -1:
            if cmp != 0:
                max_len = max(max_len, end - start + 1)
            start = end
    
    return max_len

if __name__ == "__main__":
    # Example 1
    arr1 = [9, 4, 2, 10, 7, 8, 8, 1, 9]
    print(max_turbulence_size(arr1))  # Output: 5
C#
//code by flutterfly
using System;

class Program
{
    public static int MaxTurbulenceSize(int[] arr)
    {
        int n = arr.Length;
        if (n < 2) return n;

        int maxLen = 1;
        int start = 0;
        
        for (int end = 1; end < n; ++end)
        {
            int cmp = arr[end - 1] == arr[end] ? 0 : (arr[end - 1] < arr[end] ? 1 : -1);
            
            if (end == n - 1 || cmp * (arr[end] == arr[end + 1] ? 0 : (arr[end] < arr[end + 1] ? 1 : -1)) != -1)
            {
                if (cmp != 0)
                {
                    maxLen = Math.Max(maxLen, end - start + 1);
                }
                start = end;
            }
        }
        
        return maxLen;
    }

    static void Main()
    {
        // Example 1
        int[] arr1 = { 9, 4, 2, 10, 7, 8, 8, 1, 9 };
        Console.WriteLine(MaxTurbulenceSize(arr1)); // Output: 5
    }
}
JavaScript
//code by flutterfly
function maxTurbulenceSize(arr) {
    const n = arr.length;
    if (n < 2) return n;

    let maxLen = 1;
    let start = 0;

    for (let end = 1; end < n; ++end) {
        let cmp = arr[end - 1] === arr[end] ? 0 : (arr[end - 1] < arr[end] ? 1 : -1);

        if (end === n - 1 || cmp * (arr[end] === arr[end + 1] ? 0 : (arr[end] < arr[end + 1] ? 1 : -1)) !== -1) {
            if (cmp !== 0) {
                maxLen = Math.max(maxLen, end - start + 1);
            }
            start = end;
        }
    }

    return maxLen;
}

// Example 1
const arr1 = [9, 4, 2, 10, 7, 8, 8, 1, 9];
console.log(maxTurbulenceSize(arr1)); // Output: 5

Output
5

Time Complexity: O(n), where n is the length of the array. This is because we are iterating through the array once.
Auxiliary Space: O(1) since we are using only a few extra variables to keep track of indices and the maximum length.




Reffered: https://www.geeksforgeeks.org


Arrays

Related
Minimize the Maximum Value in Two Arrays Minimize the Maximum Value in Two Arrays
Unbounded Knapsack in Python Unbounded Knapsack in Python
Dutch National Flag Problem in Python Dutch National Flag Problem in Python
Assign Campus Bikes to Workers II Assign Campus Bikes to Workers II
Assign Campus Bikes to Workers Assign Campus Bikes to Workers

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
18