Ramm
Ramm

Reputation: 23

Java longest subsequence

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);

Upvotes: 2

Views: 185

Answers (3)

wittakarn
wittakarn

Reputation: 3162

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);
}

Upvotes: 4

Tom
Tom

Reputation: 17597

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++;

Upvotes: 5

Codeek
Codeek

Reputation: 1624

Or simply make following changes

int lungmax=1;

and replace

lungmax=lung

with

lungmax++;

and remove last lungmax=lungmax++

plus what Tom suggested : k<30-1

Upvotes: 1

Related Questions