- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
- Related Articles
- Maximize the size of array by deleting exactly k sub-arrays to make array prime in C++
- Find the longest sub array of consecutive numbers with a while loop in JavaScript
- Find the longest subsequence of an array having LCM at most K in Python
- Build Array Where You Can Find The Maximum Exactly K Comparisons in C++
- Count sub-matrices having sum divisible 'k' in C++
- Find numbers with K odd divisors in a given range in C++
- Find Maximum XOR value of a sub-array of size k in C++
- C++ program to find numbers with K odd divisors in a given range
- Count all sub-arrays having sum divisible by k
- Bitwise AND of sub-array closest to K in C++
- Find k closest numbers in an unsorted array in C++
- Program to find count of numbers having odd number of divisors in given range in C++
- Program to find length of longest increasing subsequence with at least k odd values in Python
- Maximum possible middle element of the array after deleting exactly k elements in C++
- Find last k digits in product of an array numbers in C++

Advertisements