Longest Turbulent Subarray in C++

C++Server Side ProgrammingProgramming

Consider a subarray A[i], A[i+1], ..., A[j] of A is said to be turbulent when it meets these conditions −

  • For i <= k < j and A[k] > A[k+1] when k is odd, and A[k] < A[k+1] when k is even;

  • Otherwise, for i <= k < j, A[k] > A[k+1] when k is even, and A[k] < A[k+1] when k is odd.

So the subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray. Now find the length of a maximum size turbulent subarray of A. So if the input is like [9,4,2,10,7,8,8,1,9], output is 5. This is because A[1] > A[2] < A[3] > A[4] < A[5]

To solve this, we will follow these steps −

  • n := size of array A

  • prevBig := 1, prevSmall := 1, currBig := 1, currSmall := 1 and ret := 1

  • for i in range 1 to n – 1

    • if A[i] > A[i – 1], then currBig := 1 + prevSmall

    • if A[i] < A[i – 1], then currSmall := 1 + prevBig

    • ret := max of ret, currBig and currSmall

    • prevSmall := currSmall, prevBig := currBig, currSmall := 1, currBig := 1

  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int maxTurbulenceSize(vector<int>& A) {
      int n = A.size();
      int prevBig = 1;
      int prevSmall = 1;
      int currBig = 1;
      int currSmall = 1;
      int ret = 1;
      for(int i = 1; i < n; i++){
         if(A[i] > A[i - 1]){
            currBig = 1 + prevSmall;
         }
         if(A[i] < A[i - 1]){
            currSmall = 1 + prevBig;
         }
         ret = max({ret, currBig, currSmall});
         prevSmall = currSmall;
         prevBig = currBig;
         currSmall = 1;
         currBig = 1;
      }
      return ret;
   }  
};
main(){
   vector<int> v1 = {9,4,2,10,7,8,8,1,9};
   Solution ob;
   cout << (ob.maxTurbulenceSize(v1));
}

Input

[9,4,2,10,7,8,8,1,9]

Output

5
raja
Published on 10-Apr-2020 13:58:52
Advertisements