Recursion example-3 (medium):: Length of longest contiguous increasing subsequence

Length of longest contiguous increasing subsequence.


Program:

#include<stdio.h>
int len_longseq(int, int, int);              /* function prototype  */
int max=-1;                                      /* declare max variable globally   */
int main()
{
       int n,prev;  
       printf("enter number of numbers");
       scanf("%d",&n);              
       if(n>0)
       {                                                      /* if n>0 proceed  */
             scanf("%d",&prev);                 /* read first integer  */
             int count=1;                       /* initialize count to 1  */
             if(n==1)                           /* if n=1 then print count=1 and stop  */
             printf("%d",count);
             else
            {                                                     /* if n>1   */
                    count=len_longseq(prev,n-1,1);          /* function call  */
                    printf("%d",count);                             /* print output  */
             }
        }          
        return 0;
}
int len_longseq(int prev,int n,int count)      /* function definition  */
{
    if(max<count)                                  /* to keep the length of longest subsequence so far */
           max=count;
    if(n==0)                                     /* base case if n=0,return max and stop  */
          return max;
    int x;
   scanf("%d",&x);                              /* read next number  */
   if(x>prev)                                   /* if read value is greater than previous read value  */
          return(len_longseq(x,n-1,++count));
 
   return (len_longseq(x,n-1, 1));               /* if read value is not greater than previous read value  */
}

Sample input:

enter number of numbers: 7
5  6  7  8  9  1  2

Output: 5

No comments: