Help with array

Joined
Jan 8, 2023
Messages
2
Reaction score
0
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)
Please help
 
Last edited:
Joined
Jan 8, 2023
Messages
27
Reaction score
2
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;
}
 
Joined
Sep 21, 2022
Messages
122
Reaction score
15
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,763
Messages
2,569,560
Members
45,035
Latest member
HoTaKeDai

Latest Threads

Top