Header Ads Widget

Develop Your Creative Skill with
Free Design Tutorials

Our blog helps to Provide Latest Tips and Tricks tutorials about Blogging
Business, SEO Tips, much more. this Blog and stay tuned to this
blog for further updates.

Longest Turbulent subarray

 Longest Turbulent subarrays solution

We have given an Integer array we have to find the size of the longest Turbulent subarrays. Before going to solve this problem we have to understand what is Turbulent subarray?
   A subarray is said to be Turbulent if the comparison sign between each adjacent pair of items in a subarray flips, the subarray is turbulent.

Let us see some examples for better understanding Turbulent subarrays.

Input: arr = [2,7,34,8,9,21,45,12]
Output: 4


Example 2:
Input: arr = [10,3,12,30,28,3]
Output: 3

Example 3:
Input: arr = [20]
Output: 1


Longest Turbulent subarray


Solution of a Longest turbulent subarray in Java


class Solution {
    public int maxTurbulenceSize(int[] arr) {
        if(arr.length==1return 1;
        if(arr.length==2 && arr[0]!=arr[1]) return 2;
       boolean b=true;
        for(int i=0;i<arr.length;i++)
        {
            if(arr[0]!=arr[i]) b=false;
            if(!b) break;
        }
        if(b) return 1;
        int count=2;
        int max=0;
        for(int i=1;i<arr.length-1;i++)
        {
            
            if((arr[i]>arr[i-1] && arr[i]>arr[i+1]) || (arr[i]<arr[i-1] && arr[i]<arr[i+1]))
            {
               
               count=count+1;
            }
            else
            {
                count=2;
            }
           if(arr[i-1]!=arr[i]) max=Math.max(max,count);
            
            
        }

        return max;
        
        
    }
}

Solution of a Longest turbulent subarray in C++


class Solution {
  
   int maxTurbulenceSize(vector<int>& arr) {
        int max = 0c = 1;
        if (arr.size() == 1return 1;
        
        bool b
        for (int i = 0i < arr.size() - 1; ++i) {
            if (arr[i] == arr[i + 1]) {
                max = c > max ? c : max;
                c = 1;
            }
             else if((c == 1) || ((arr[i] > arr[i + 1] ? true : false) ^ b)) { 
                 c++;
                 b = arr[i] > arr[i + 1] ? 1 : 0;
             }
             else {
                 max = c > max ? c : max;
                 c = 1;
                 --i;
             }
        }
        max = c > max ? c : max;
        return max;
    }
};


The above codes are most efficient and with very little time C    complexity you can your own approach to getting a more efficient and optimized solution.