Longest Zig-Zag Sub Sequence - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Friday 12 July 2019

Longest Zig-Zag Sub Sequence



The longest Zig-Zag subsequence problem is to find length of the longest subsequence of given sequence such that all elements of this are alternating.
If a sequence {x1, x2, .. xn} is alternating sequence then its element satisfy one of the following relation :
 x1 < x2 > x3 < x4 > x5 < …. xn or 
  x1 > x2 < x3 > x4 < x5 > …. xn 

#include <iostream>
using namespace std;

int main() {
//code
int t;
cin>>t;
while(t--){
    int n;
    cin>>n;
    int a[n],cnt=0;
    
    for(int i=0;i<n;i++)
       cin>>a[i];
       int flag=0;
    for(int i=0;i<n-1;i=i+1){
        if(a[i]<a[i+1]&&flag==0)
        {
            cnt++;
            flag=1;
        }else if(a[i]>a[i+1]&&flag==1){
            cnt++;
            flag=0;
        }
    }
    if(n==1){
        cout<<a[0]<<endl;
    }else if(a[0]>a[1]){
    cout<<(cnt+2)<<endl;}//added both last and first element
else{
        cout<<(cnt+1)<<endl; //added only last element
    }
}
return 0;
}