Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java longest subsequence

Tags:

java

I have an array, i'd like to calculate the length of the longest subsequence made by equals numbers: Example: 5 1 1 9 9 9 4 4 6 6 4 4 4 --> the length of the longest subsequence is 3 (9 9 9). This is what i got so far but it doesn't work.

int lung=0, lungmax=0;
        int indice = 0;
        int [] values = new int [30];  
        for(int k=0; k<30; k++)
        {
            if (values[k]==values[k+1])
            {
                lung++;
                if (lung>lungmax)
                {
                    lungmax=lung;
                    indice=values[k];
                }
            }   
            else lung=0;
        }

        lungmax = lungmax++;
    System.out.println("the length of the longest subsequence is: "+lungmax);
like image 521
Ramm Avatar asked Dec 05 '25 12:12

Ramm


2 Answers

Your code has two errors:

for(int k=0; k<30; k++) {
    if (values[k]==values[k+1]) {

This loop will be executed until k reaches value 30. Therefore, the last used value for k is 29. If you use that value in the if statement, you'll exceed that array bounds by calling values[k+1] (== values[30]).

Change that loop to:

for(int k = 0; k < values.length - 1; k++) {

The second problem is this line:

lungmax = lungmax++;

This is the same as:

int temp = lungmax;
lungmax = lungmax + 1;
lungmax = temp;

As you can see, you're "ignoring" the increment. Change that line to:

lungmax++;
like image 95
Tom Avatar answered Dec 07 '25 01:12

Tom


Try this. By applying my approach, the ArrayIndexOutOfBoundsException has been eliminated.

public static void main(String args[]) {
    int lung = 1, lungmax = 0;
    int indice = 0;
    int[] values = {1, 2, 2, 3, 3, 3, 5, 5, 5, 5, 6};
    for (int k = 1; k < values.length; k++) {

        if (values[k - 1] == values[k]) {
            lung++;
            if (lung > lungmax) {
                lungmax = lung;
                indice = values[k];
            }
        } else {
            lung = 1;
        }
    }
    System.out.println("the length of the longest subsequence is: " + indice + "/" + lungmax);
}
like image 42
wittakarn Avatar answered Dec 07 '25 01:12

wittakarn