Skip to content
Related Articles

Related Articles

Maximum even numbers present in any subarray of size K
  • Difficulty Level : Medium
  • Last Updated : 15 Jan, 2021

Given an array arr[] of size N and an integer K, the task is to find the maximum number of even numbers present in any subarray of size K.

Examples:

Input: arr[] = { 2, 3, 5, 4, 7, 6 }, K = 3 
Output:
Explanation: 
Subarrays of size K(=3) with maximum count of even numbers are { arr[3], arr[4], arr[5] } 
Therefore, the required output is 2

Input: arr[] = { 4, 3, 2, 6 }, K = 2 
Output: 2

Naive Approach: The simplest approach to solve this problem is to generate all possible subarrays of size K and count the even numbers in the subarray. Finally, print the maximum count obtained.



Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum count of
// even numbers from all the subarrays of
// size K
int maxEvenIntegers(int arr[], int N, int M)
{
 
    // Stores the maximum count of even numbers
    // from all the subarrays of size K
    int ans = 0;
 
    // Generate all subarrays of size K
    for (int i = 0; i <= N - M; i++) {
 
        // Store count of even numbers
        // in current subarray of size K
        int cnt = 0;
 
        // Traverse the current subarray
        for (int j = 0; j < M; j++) {
 
            // If current element
            // is an even number
            if (arr[i + j] % 2 == 0)
                cnt++;
        }
 
        // Update the answer
        ans = max(ans, cnt);
    }
 
    // Return answer
    return ans;
}
 
// Driver Code
int main()
{
 
    int arr[] = { 2, 3, 5, 4, 7, 6 };
    int K = 3;
 
    // Size of the input array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    cout << maxEvenIntegers(arr, N, K) << endl;
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above approach
import java.util.*;
class GFG
{
 
// Function to find the maximum count of
// even numbers from all the subarrays of
// size K
static int maxEvenIntegers(int arr[], int N, int M)
{
 
    // Stores the maximum count of even numbers
    // from all the subarrays of size K
    int ans = 0;
 
    // Generate all subarrays of size K
    for (int i = 0; i <= N - M; i++)
    {
 
        // Store count of even numbers
        // in current subarray of size K
        int cnt = 0;
 
        // Traverse the current subarray
        for (int j = 0; j < M; j++)
        {
 
            // If current element
            // is an even number
            if (arr[i + j] % 2 == 0)
                cnt++;
        }
 
        // Update the answer
        ans = Math.max(ans, cnt);
    }
 
    // Return answer
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 2, 3, 5, 4, 7, 6 };
    int K = 3;
 
    // Size of the input array
    int N = arr.length;
    System.out.print(maxEvenIntegers(arr, N, K) +"\n");
 
}
}
 
// This code is contributed by 29AjayKumar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approach
 
# Function to find the maximum count of
# even numbers from all the subarrays of
# size K
def maxEvenIntegers(arr, N, K):
   
    # Stores the maximum count of even numbers
    # from all the subarrays of size K
    ans = 0
    # Generate all subarrays of size K
    for i in range(N-K+1):
        # Store count of even numbers
        # in current subarray of size K
        cnt = 0
 
        # Traverse the current subarray
        for j in range(0, K):
            if arr[i+j] % 2 == 0:
                cnt += 1
        # Update the answer
        ans = max(cnt, ans)
    # Return answer
    return ans
 
 
# Driver Code
if __name__ == '__main__':
    arr = [2, 3, 5, 4, 7, 6]
    K = 3
    # Size of the input array
    N = len(arr)
    print(maxEvenIntegers(arr, N, K))
 
# This code is contributed by MuskanKalra1

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
 
class GFG
{
   
    // Function to find the maximum count of
    // even numbers from all the subarrays of
    // size K
    static int maxEvenIntegers(int []arr, int N, int M)
    {
     
        // Stores the maximum count of even numbers
        // from all the subarrays of size K
        int ans = 0;
     
        // Generate all subarrays of size K
        for (int i = 0; i <= N - M; i++)
        {
     
            // Store count of even numbers
            // in current subarray of size K
            int cnt = 0;
     
            // Traverse the current subarray
            for (int j = 0; j < M; j++)
            {
     
                // If current element
                // is an even number
                if (arr[i + j] % 2 == 0)
                    cnt++;
            }
     
            // Update the answer
            ans = Math.Max(ans, cnt);
        }
     
        // Return answer
        return ans;
    }
     
    // Driver Code
    public static void Main(string[] args)
    {
        int []arr = { 2, 3, 5, 4, 7, 6 };
        int K = 3;
     
        // Size of the input array
        int N = arr.Length;
        Console.WriteLine(maxEvenIntegers(arr, N, K));
    }
}
 
// This code is contributed by AnkThon

chevron_right


Output: 

2

 

Time Complexity: O(N * K) 
Auxiliary Space: O(1)

Efficient Approach: The above approach can be optimized using Sliding window technique. Follow the steps below to solve the problems:

  • Initialize a variable, say cntMaxEven, to store the maximum count of even numbers in a subarray of size K.
  • Calculate the count of even numbers in the subarray { arr[0], … arr[K – 1] } and store it into cntMaxEven.
  • Traverse the remaining subarrays of size K by iterating over the range [K, N – 1]. For every ith iteration remove the first element of the subarray and insert the current ith element of the array into the current subarray.
  • Count the even numbers in the current subarray and update cntMaxEven to maximum of count of even numbers in the current subarray and cntMaxEven.
  • Finally, print the value of cntMaxEven.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum count of
// even numbers from all the subarrays of
// size K
int maxEvenIntegers(int arr[], int N, int M)
{
 
    // Stores the count of even numbers
    // in a subarray of size K
    int curr = 0;
 
    // Calculate the count of even numbers
    // in the current subarray
    for (int i = 0; i < M; i++) {
 
        // If current element is
        // an even number
        if (arr[i] % 2 == 0)
            curr++;
    }
 
    // Stores the maximum count of even numbers
    // from all the subarrays of size K
    int ans = curr;
 
    // Traverse remaining subarrays of size K
    // using sliding window technique
    for (int i = M; i < N; i++) {
 
        // If the first element of
        // the subarray is even
        if (arr[i - M] % 2 == 0) {
 
            // Update curr
            curr--;
        }
 
        // If i-th element is even increment
        // the count
        if (arr[i] % 2 == 0)
            curr++;
 
        // Update the answer
        ans = max(ans, curr);
    }
 
    // Return answer
    return ans;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 3, 5, 4, 7, 6 };
    int M = 3;
 
    // Size of the input array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    cout << maxEvenIntegers(arr, N, M) << endl;
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above approach
import java.util.*;
 
class GFG
{
 
  // Function to find the maximum count of
  // even numbers from all the subarrays of
  // size K
  static int maxEvenIntegers(int arr[], int N, int M)
  {
 
    // Stores the count of even numbers
    // in a subarray of size K
    int curr = 0;
 
    // Calculate the count of even numbers
    // in the current subarray
    for (int i = 0; i < M; i++)
    {
 
      // If current element is
      // an even number
      if (arr[i] % 2 == 0)
        curr++;
    }
 
    // Stores the maximum count of even numbers
    // from all the subarrays of size K
    int ans = curr;
 
    // Traverse remaining subarrays of size K
    // using sliding window technique
    for (int i = M; i < N; i++)
    {
 
      // If the first element of
      // the subarray is even
      if (arr[i - M] % 2 == 0)
      {
 
        // Update curr
        curr--;
      }
 
      // If i-th element is even increment
      // the count
      if (arr[i] % 2 == 0)
        curr++;
 
      // Update the answer
      ans = Math.max(ans, curr);
    }
 
    // Return answer
    return ans;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int arr[] = { 2, 3, 5, 4, 7, 6 };
    int M = 3;
 
    // Size of the input array
    int N = arr.length;
 
    // Function call
    System.out.print(maxEvenIntegers(arr, N, M) +"\n");
 
  }
}
 
// This code is contributed by 29AjayKumar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approach
 
# Function to find the maximum count of
# even numbers from all the subarrays of
# size M
def maxEvenIntegers(arr, N, M):
   
    # Stores the count of even numbers
    # in a subarray of size M
    curr = 0
     
    # Calculate the count of even numbers
    # in the current subarray
    for i in range(0, M):
       
        # If current element is
        # an even number
        if(arr[i] % 2 == 0):
            curr += 1
             
    # Stores the maximum count of even numbers
    # from all the subarrays of size M
    ans = curr
     
    # Traverse remaining subarrays of size M
    # using sliding window technique
    for i in range(M, N):
       
        # If the first element of
        # the subarray is even
        if(arr[i - M] % 2 == 0):
           
            # update curr
            curr -= 1
             
        # If i-th element is even increment
        # the count
        if(arr[i] % 2 == 0):
            curr += 1
             
            # update the answer
            ans = max(curr, ans)
             
    # Return answer
    return ans
 
# Driver Code
if __name__ == '__main__':
    arr = [2, 3, 5, 4, 7, 6]
    M = 3
     
    # Size of the input array
    N = len(arr)
     
    # Function call
    print(maxEvenIntegers(arr, N, M))
 
# This code is contributed by MuskanKalra1

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
 
class GFG
{
 
  // Function to find the maximum count of
  // even numbers from all the subarrays of
  // size K
  static int maxEvenints(int []arr, int N, int M)
  {
 
    // Stores the count of even numbers
    // in a subarray of size K
    int curr = 0;
 
    // Calculate the count of even numbers
    // in the current subarray
    for (int i = 0; i < M; i++)
    {
 
      // If current element is
      // an even number
      if (arr[i] % 2 == 0)
        curr++;
    }
 
    // Stores the maximum count of even numbers
    // from all the subarrays of size K
    int ans = curr;
 
    // Traverse remaining subarrays of size K
    // using sliding window technique
    for (int i = M; i < N; i++)
    {
 
      // If the first element of
      // the subarray is even
      if (arr[i - M] % 2 == 0)
      {
 
        // Update curr
        curr--;
      }
 
      // If i-th element is even increment
      // the count
      if (arr[i] % 2 == 0)
        curr++;
 
      // Update the answer
      ans = Math.Max(ans, curr);
    }
 
    // Return answer
    return ans;
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    int []arr = { 2, 3, 5, 4, 7, 6 };
    int M = 3;
 
    // Size of the input array
    int N = arr.Length;
 
    // Function call
    Console.Write(maxEvenints(arr, N, M) +"\n");
  }
}
 
// This code is contributed by 29AjayKumar

chevron_right


Output: 

2

 

Time Complexity: O(N)

Auxiliary Space: O(1)

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :