patternjavaMinor
Print length of longest sequence of consecutive numbers
Viewed 0 times
lengthnumberssequenceprintlongestconsecutive
Problem
Problem H (Longest 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.
Example:
This is my code so far:
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.
Example:
Input 7 2 3 5 6 7 9 10
Output 3This is my code so far:
import java.util.Scanner;
public class Conse {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int x=scan.nextInt();
int[] array= new int[x];
for(int i=0;i<array.length;i++)
array[i]=scan.nextInt();
System.out.println(array(array));
}
public static int array(int[] array){
int count=0,temp=0;
for(int i=0;i<array.length;i++){
count=0;
for(int j=i,k=i+1;j<array.length-1;j++,k++)
if(array[j]-array[k]==1)
count++;
else{if(temp<count)
temp=count;
break;}
}
return temp+1;
}
}Solution
Using
Your function crashes on arrays of length 0 or 1.
The variable names
static for the consecutive() function is appropriate. However, the omission of braces, the inconsistent indentation, and lack of spaces between operators is just as bad as before.Your function crashes on arrays of length 0 or 1.
The variable names
f and counter could be improved. I think that a different looping structure would be clearer as well.public static int consecutive(int[] array) {
if (array.length <= 1) {
return array.length;
}
int maxRun = 0;
for (int i = 1; i < array.length; i++) {
int thisRun = 1;
while (i < array.length && array[i - 1] + 1 == array[i]) {
thisRun++;
i++;
}
if (maxRun < thisRun) {
maxRun = thisRun;
}
}
return maxRun;
}Code Snippets
public static int consecutive(int[] array) {
if (array.length <= 1) {
return array.length;
}
int maxRun = 0;
for (int i = 1; i < array.length; i++) {
int thisRun = 1;
while (i < array.length && array[i - 1] + 1 == array[i]) {
thisRun++;
i++;
}
if (maxRun < thisRun) {
maxRun = thisRun;
}
}
return maxRun;
}Context
StackExchange Code Review Q#71578, answer score: 5
Revisions (0)
No revisions yet.