How to find the longest sequence of consecutive natural successors?

Two consecutive integers are natural successors if the second is the successor of the first in the sequence of natural numbers (1 and 2 are natural successors). Write a program that reads a number N followed by N integers, and then prints the length of the longest sequence of consecutive natural successors.

import java.util.Scanner;

public class objects {
    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int x = scan.nextInt();
        int nmbr[] = new int[x];
        for(int f=0;f<nmbr.length;f++)
            nmbr[f]=scan.nextInt();
        int counter = 0;
        int max = 0;
        for (int i = 0; i < nmbr.length - 1; i++) {
            if (nmbr[i] == (nmbr[i + 1]-1))
                counter++;
            else
                counter = 0;
            if (counter > max)
                max = (counter+1);
        }
        System.out.println(max);
    }
}

Why is my code still printing the counter without adding one? I am not finding the mistake sample run:

     7 2 3 5 6 7 9 10 
     2

it is printing 2 instead of 3.

Jon Skeet
people
quotationmark

When you see the first number out of sequence, you should reset counter to 1, not 0 - as it's the start of a sequence with length at least 1. You then need to also change the code which changes max:

if (counter > max) {
    counter = max;
}

After all, you just want max to be the maximum value of counter.

(I would strongly recommend using braces for every if statement, by the way - it's easier to avoid mistakes that way.)

people

See more on this question at Stackoverflow