Find the longest sub-array having exactly k odd numbers in C++


Suppose we have one array with n elements. The problem is to find longest sub-array which has exactly k odd numbers. So if A = [2, 3, 4, 11, 4, 12, 7], and k = 1, then output will be 4, sub-array is [4, 11, 4, 12]

We can solve this using sliding window. The task is like below −

  • Initialize max := 0, count := 0, and start := 0
  • for i in range 0 to n – 1, do the following
    • if arr[i] mod 2 is not 0, then increase count by 1
    • while count > k and start <= i, do the following
      • if arr[start] mod 2 is not 0, then decrease count by 1
      • increase start by 1
    • if count = k, then
      • if max < (i – start + 1), then max := (i – start + 1)
    • return the max

Example

 Live Demo

#include<iostream>
using namespace std;
int oddSubarrayMaxLength(int arr[], int n, int k) {
   int max_len = 0, count = 0, start = 0;
   for (int i = 0; i < n; i++) {
      if (arr[i] % 2 != 0)
         count++;
      while (count > k && start <= i)
         if (arr[start++] % 2 != 0)
            count--;
      if (count == k)
      if (max_len < (i - start + 1))
      max_len = i - start + 1;
   }
   return max_len;
}
int main() {
   int arr[] = {2, 3, 4, 11, 4, 12, 7};
   int n = sizeof(arr) / sizeof(arr[0]);
   int k = 1;
   cout << "Maximum Length is: "<< oddSubarrayMaxLength(arr, n, k);
}

Output

Maximum Length is: 4

Updated on: 18-Dec-2019

53 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements