Find the count of maximum contiguous Even numbers in C++


Suppose we have an array A with n elements. We have to find the maximum number of the contiguous even numbers in the given array. So if the array is like A = [1, 2, 3, 4, 6, 8, 7], then the count will be 3.

We can solve this easily. We need two count variables one is max_current, and another is max_till_now. If an even number is found, then increase max_current, then compare it with max_till_now. Every time an odd element is found reset max_count to 0.

Example

 Live Demo

#include<iostream>
using namespace std;
int maxEvenContiguous(int arr[], int n) {
   int max_current = 0, max_till_now = 0;
   for (int i = 0; i < n; i++) {
      if (arr[i] % 2 != 0)
         max_current = 0;
      else {
         max_current++;
         max_till_now = max(max_current, max_till_now);
      }
   }
   return max_till_now;
}
int main() {
   int arr[] = {1, 2, 3, 4, 6, 8, 7};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Max contiguous even number count: " << maxEvenContiguous(arr, n);
}

Output

Max contiguous even number count: 3

Updated on: 17-Dec-2019

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements