How to report the highest consecutive sequence? [closed]

0

I'm hooked on this algorithm where I create an integer vector with n positions and need to show the largest consecutive sequence.

I'll leave the statement to try to be more specific.

"Create an algorithm where the user types 50 integers of a vector and at the end the program informs the size of the largest consecutive sequence increasing."

ex:

6,7,9. GreaterSequence = 2.

5,6,7,8,11. GreaterSequence = 4

What I've done so far:

public class Questao02 {

        public static void main(String[] args){
            String aux;
            int a[] = new int[5];
            int cont=0;

            for(int i=0;i<5;i++){
                aux = JOptionPane.showInputDialog("Números");
                a[i] = Integer.parseInt(aux);

                if(a[i] < a[i+1] ){
                    cont++;

                }

                else{
                    cont=0;

                }

            }

            System.out.println(cont);
        }
}
    
asked by anonymous 03.09.2017 / 15:32

1 answer

0

It is important to separate the introduction of the values from the accounting logic. In this case even simplifies because the accounting can not be done for all values because it considers the value of the front, so it has to finish one before the end.

It also needs another variable to store the maximum sequence found so far, otherwise when cont returns to 0 it loses the previous sequence that could even be greater.

public static void main(String[] args) {
    int a[] = new int[5];
    int cont = 0;
    int maior = 0; //nova variável para a maior sequencia achada

    //só a leitura
    for(int i=0;i<5;i++){
        //sem aux para simplificar
        a[i] = Integer.parseInt(JOptionPane.showInputDialog("Números"));
    }

    //só a contabilização
    for(int i=0;i<4;i++){ //até ao 4, um antes do fim
        if(a[i] == a[i+1]-1){ //teste de valor 1 abaixo, em vez de apenas inferior
            cont++;

            //verifica e atualiza com a maior sequência
            if (cont > maior){  achada até ao momento
                maior = cont;
            }
        }
        else{
            cont=0;
        }
    }

    //quando testa se o número é sequencia com o da frente o maior vai ficar com 1 mas
    //a sequência já representa dois números, logo é necessário no fim somar 1
    maior++;
    System.out.println(maior);
}

Considerations:

  • Just like Articuno, it's not a good idea to mix graphical interface and console mode, so consider using Scanner and nextInt() to read by consistency.
  • The parseInt can throw an exception if the user does not enter a number. Consider therefore using exception handling with try catch if you want to prevent the program from crashing in that case.
03.09.2017 / 17:06