2

I am stuck doing an assignment for university. The task is to find a recursive and then dynamic programming way to calculate the length of the longest,consequent,ascending subsequence of an array. If the array for example is: {4 , -5 , -3, -2, 5, -2, 0, 3 , 2} the maximal length would be 4 with the subsequence {-5, -3, -2, 5}. I have trouble finding a recursive way and without a recursive way it's impossible to find a dynamnic way for me.
I have tried programming something but I know it's wrong and I am not sure how to fix it:

public static int length(int[] arr,int j)
{
    if(arr.length == 1)
    {
        return 1;
    }
    if(j == 1)
    {
        if(arr[j-1] < arr[j])
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }
    else
    {
        int c = length(arr,j-1);
        if(arr[j-1] < arr[j])
        {
            return 1 + c;
        }
        else
        {
            return 0;
        }
    }
}
Rard
  • 41
  • 5

1 Answers1

0

Try this :

int length(int index, int previous)
    {
       if(arr.length == (index+1))
            return 0;
       else 
           if(arr[index] > previous)
               return 1+length(index+1,arr[index]);
           else return length(index+1,previous)
    }

Maybe you don't need to give the array as argument in each recursive call by making a static variable,

Previous is the latest element of the subsequence

Othman Benchekroun
  • 1,998
  • 2
  • 17
  • 36