You shouldn't have to use a temporary list for this. Just loop through the array or list with a counter and increment for each element that is greater than or equal to the previous. Use another variable to store the maximum:
int[] a = { 1, 2, 3, 4, 0, 19, 1, 1, 2, 2, 3, 3, 2 };
int count = 1, max = 1;
for (int i = 1; i < a.length; i++) {
if (a[i] >= a[i - 1]) {
count++;
} else {
count = 1;
}
if (count > max) {
max = count;
}
}
System.out.println(max);
6
Here, count
is the number of contiguous and sorted elements. We increment it while we're on a continuous/increasing streak. Once this streak breaks (else
clause), we check if count
is greater than max
, our variable for storing the maximum count: if it is, we set max
to count
. We then set count
back to 1, since in the else
clause we know our streak has ended and we'll need to start over.
(I've used an array here, but it should be trivial to convert the above code to work with lists).