Friday 20 April 2012

Find Maximum Possible Zig-Zag subsequence in a sequence

/*
Start with the first 2 elements. If the 2 element is greater than first , then next you have to find the reducing number and viceversa.
If you find lets say the 3rd number also to be increasing, then take 3rd number as your sequence number rather than 2nd, i.e, replace 2nd number with 3rd number. and go on like this till the end.

Example:

Initial sequence : 5 6 4 2 100 25 32 35
Final seq: 5 6 (Increasing)
Final seq: 5 6 4(Decreasing)
Final seq: 5 6 2(Decreasing, replace 4 with 2)
...
..
Final seq: 5 6 2 100 25 35

*/

#include "iostream"
#include "vector"
using namespace std;

enum STATE
{
     UNKNOWN,
     NEED_TO_INCREASE,
     NEED_TO_DECREASE
};

int main()
{
     STATE state = UNKNOWN;
     int noOfElements,temp;
     vector<int> arraylist;
     vector<int> finalsequence;
     int lastelement;
     bool isIncreased;
     cout<<"Enter the number of elements in array : ";
     cin>>noOfElements;
     cout<<"Enter the elements"<<endl;
     for(int i=0;i<noOfElements;i++)
     {
          cin>>temp;
          arraylist.push_back(temp);
     }
     finalsequence.push_back(arraylist[0]);
     int index = 0;
   
     while((++index) < noOfElements)
    {
          switch(state)
         {
               case UNKNOWN:
                    if(arraylist[index] > arraylist[0])    
                         state = NEED_TO_DECREASE;  
                    else if(arraylist[index] < arraylist[0])    
                         state = NEED_TO_INCREASE;  
                    finalsequence.push_back(arraylist[index]);
                    lastelement = arraylist[index]; 
                    break;
               case NEED_TO_INCREASE: 
                    if(arraylist[index] > lastelement)
                   {   
                         finalsequence.push_back(arraylist[index]);
                         state = NEED_TO_DECREASE;
                    }else    
                          finalsequence[finalsequence.size()-1] = arraylist[index];
                     lastelement = arraylist[index];
                     break;
               case NEED_TO_DECREASE: 
                     if(arraylist[index] < lastelement)
                    {   
                          finalsequence.push_back(arraylist[index]);
                          state = NEED_TO_INCREASE;
                     }else    
                          finalsequence[finalsequence.size()-1] = arraylist[index];
                     lastelement = arraylist[index];
                     break; 
           }
     } 

     vector<int>::iterator itr = finalsequence.begin();
      while(itr != finalsequence.end())
     {
           cout<<*itr<<" ";
           itr++;
      }
      return 0;
}

1 comment:

Andy said...

I somehow not convinced with this, but accepting as not able to find a counter example.