Issue
In this program I am trying to show the longest consecutive numbers.
(For example: input: 1 1 1 2 2 2 2 3 3 3 3 3
, output: 3 4 5
)
My question is how can I show only the largest number from my output. In this example 5
.
We are not allowed to use Arrays, is there any other way to solve this problem?
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int zahl = 0;
int anzahl = -1;
String maxString = "";
while (sc.hasNextInt()) {
int i = sc.nextInt();
if (anzahl == i | anzahl == -1) {
zahl++;
} else if(anzahl != i) {
maxString += zahl + "\n" ;
zahl = 1;
}
anzahl = i;
}
sc.close();
System.out.println(maxString + (zahl + 1));
}
Solution
Just create a variable to track the maximum number outside the loop, and change it when new subsequence is detected and after the loop to check the length of the last subsequence:
Scanner sc = new Scanner("1 1 1 2 2 2 2 2 3 3 3 4 4 4 4 4 4 5 5 5");
int zahl = 0;
int anzahl = -1;
String maxString = "";
int maxFreq = 0; // maximal frequency of numbers
while (sc.hasNextInt()) {
int i = sc.nextInt();
if(anzahl == i || anzahl == -1) {
zahl++;
} else {
maxFreq = Math.max(maxFreq, zahl); // update maxFreq
maxString += zahl + "\n" ;
zahl = 1;
}
anzahl = i;
}
maxFreq = Math.max(maxFreq, zahl); // check the tail
sc.close();
//System.out.println(maxString + (zahl + 1) );
System.out.println("maxFreq=" + maxFreq);
prints maxFreq=6
(the count of 4
s).
For this input Scanner sc = new Scanner("1 1 1 2 2 2 2 2 2 2");
the code prints maxFreq=7
Answered By - Alex Rudenko
Answer Checked By - Clifford M. (JavaFixing Volunteer)