Count the increasing elements in an array

I am trying to read the longest string of sequentially incrementing elements in a randomly generated MOODS array. This code always returns less than correct.

int maxDays = 0; int days = 0; for (int i = 0; i < MOODS.size() - 1; i++) { if (MOODS.get(i + 1) > MOODS.get(i)) { days += 1; if(days>maxDays){ maxDays=days; } } else { days = 0; } } return maxDays; } 
+6
source share
1 answer

You will always have at least one ascending sequence of lines with a length of 1. Just change the days to 1 and they will work.

 int maxDays = Math.min(1, MOODS.size()); int days = 1; for (int i = 0; i < MOODS.size() - 1; i++) { if (MOODS.get(i + 1) > MOODS.get(i)) { days += 1; if (days>maxDays){ maxDays=days; } } else { days = 1; } } return maxDays; 
+5
source

Source: https://habr.com/ru/post/1012875/


All Articles