# Help with array

#### ido123

Hello I need to write a function that only takes an array as parameter(this is the one and only parameter) but u can variables
The method should return the maximum number of values in a row that their sum is divisible by 2 for example
For [2,5] it returns 1 because 2 is divisble by2
For [2,1,2] also 1 becasue only 2 is divisble by in a row
For [4,2,4] it returns 3
For [3,3,1] returns 2
In the complexity of O(n)

Last edited:

#### AngleWyrm

Why does f( [2,1,2] ) return 1, but f( [4,2,4] ) return 3?

#### ido123

Why does f( [2,1,2] ) return 1, but f( [4,2,4] ) return 3?
Correct because in 2,1,2 the sum of one slot is divisble by 2
for 4,2,4 The sum of 3 slots are divisible by 2

#### thugbunny

To solve this problem in O(n) time complexity in Java, you can iterate through the array and keep track of the current count of elements whose sum is divisible by 2. Whenever you encounter a element that is not divisible by 2, reset the count to 1.

JavaScript:
``````public static int maxValues(int[] arr) {
// Initialize maximum count and current count to 1
int maxCount = 1;
int curCount = 1;

// Iterate through the array
for (int i = 1; i < arr.length; i++) {
// If the current element is divisible by 2, increment the current count
if (arr[i] % 2 == 0) {
curCount++;
}
// Otherwise, reset the current count to 1
else {
curCount = 1;
}
// Update the maximum count if necessary
maxCount = Math.max(maxCount, curCount);
}

// Return the maximum count
return maxCount;
}``````

#### WhiteCube

If the sum of the whole array is even, then the answer is n.

If not, one odd number must be cut off.

Let A be the position of the first odd number.
Let Z be the position of the last odd number.

The answer is Z or n-(A+1), whichever is greater.