6

I'm trying to count the longest string of consecutively increasing elements in a randomly generated array, MOODS. This code always returns one less than what is 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;
}
  • 2
    I think that you ignore the fact that when MOODS.get(i + 1) > MOODS.get(i) for the first time, when days=0, the increasing sequence of strings has the length of two. Fix that and it should work. – Ufuk Can Bicici Dec 04 '16 at 23:10
  • Oh man, I spent so long banging my head against that error... Thank you so much. – olwatshisface Dec 04 '16 at 23:38
  • You are welcome :). The code in the answer will solve the problem and handles the special case of MOODS.size()=0 as well. – Ufuk Can Bicici Dec 04 '16 at 23:41
  • Possible duplicate of [How to determine the longest increasing subsequence using dynamic programming?](http://stackoverflow.com/questions/2631726/how-to-determine-the-longest-increasing-subsequence-using-dynamic-programming) – Julien Lopez Dec 05 '16 at 11:59

1 Answers1

5

You will always have at least one increasing sequence of string with the length of 1. Just change days to 1 and it 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;
Ufuk Can Bicici
  • 3,589
  • 4
  • 28
  • 57