Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count increasing elements in an array

Tags:

java

arrays

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;
}
like image 637
olwatshisface Avatar asked Dec 04 '16 23:12

olwatshisface


People also ask

How do you count occurrences of each element in an array?

The frequency of an element can be counted using two loops. One loop will be used to select an element from an array, and another loop will be used to compare the selected element with the rest of the array. Initialize count to 1 in the first loop to maintain a count of each element.

How many increasing Subarrays are there in the array?

So, total of 6 subarrays are increasing. Note:You only need to implement the given function.

How do you increment an array of elements?

To increment a value in an array, you can use the addition assignment (+=) operator, e.g. arr[0] += 1 . The operator adds the value of the right operand to the array element at the specific index and assigns the result to the element.

How do you know if an array is increasing?

Below are the steps: If arr[1] > arr[0], then check for strictly increasing then strictly decreasing as: Check for every consecutive pair until at any index i arr[i + 1] is less than arr[i]. Now from index i + 1 check for every consecutive pair check if arr[i + 1] is less than arr[i] till the end of the array or not.


1 Answers

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;
like image 79
Ufuk Can Bicici Avatar answered Sep 28 '22 13:09

Ufuk Can Bicici