You do not need to use a temporary list for this. Just loop the array or list using a counter and increment for each element that is greater than or equal to the previous one. Use another variable to keep 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 increase it while we are on a continuous / growing strip. As soon as this strip is broken (the else clause), we check whether count max greater than our variable to store the maximum value: if so, we set max to count . Then we set count back to 1, because in the else clause we know that our line has ended, and we will need to start all over again.
(I used an array here, but to convert the code above to work with lists should be trivial).
source share