Table of Contents
First approach
Example
Output
Description of the above code
Second One approach
Explanation of the above code
Understanding Loops
Conclusion
Home Backend Development C++ Programming in C++, find the number of subarrays with m odd numbers

Programming in C++, find the number of subarrays with m odd numbers

Sep 11, 2023 am 08:09 AM
c programming Odd number of subarrays

Programming in C++, find the number of subarrays with m odd numbers

If you have ever used C, you must know what subarrays are and how useful they are. As we all know that in C we can solve multiple mathematical problems easily. So, in this article, we will explain how to find the complete information of M odd numbers in C with the help of these subarrays.

In this problem, we need to find a number of subarrays consisting of a given array and integers m, where each subarray contains exactly m odd numbers. Here is a simple example of this approach -

Input : array = { 6,3,5,8,9 }, m = 2
Output : 5
Explanation : Subarrays with exactly 2 odd numbers are
{ 3,5 }, { 6,3,5 }, { 3,5,8 }, { 5,8,9 }, { 6,3,5,8 }, { 3,5,8,9 }

Input : array = { 1,6,3,2,5,4 }, m = 2
Output : 6
Explanation : Subarrays with exactly 2 odd numbers are
{ 1,6,3 }, { 3,2,5 }, { 1,6,3,2 }, { 6,3,2,5 }, { 3,2,5,4 }, { 6,3,2,5,4 }
Copy after login

First approach

In this approach all possible sub-arrays are generated from the given array and each sub-array is checked Whether the array has exactly m odd numbers. This is a simple generation and lookup method with a time complexity of O(n2).

Example

#include <bits/stdc++.h>
using namespace std;
int main (){
    int a[] = { 1, 6, 3, 2, 5, 4 };
    int n = 6, m = 2, count = 0; // n is size of array, m numbers to be find in subarrays,
                              // count is number of subarray with m odd numbers
    for (int i = 0; i < n; i++){ // outer loop to process each element.
        int odd = 0;
        for (int j = i; j < n; j++) {// inner loop to find subarray with m number
            if (a[j] % 2)
                odd++;
            if (odd == m) // if odd numbers become equals to m.
                count++;
        }
    }
    cout << "Number of subarrays with n numbers are: " << count;
    return 0;
}
Copy after login

Output

Number of subarrays with n numbers are: 6
Copy after login
Copy after login

Description of the above code

In this code, we use nested loops to find m odd subarrays , the outer loop is used to increment "i", which will be used to process each element in the array.

The inner loop is used to find subarrays and process elements until the odd counter reaches m, increment the result counter count for each subarray found, and finally print the result stored in the count

Second One approach

Another approach is to create an array to store the "i" number of odd prefixes, process each element, and increment the number of odd numbers each time an odd number is found.

When the number of odd numbers exceeds or equals m, add the number at the (odd - m) position in the prefix array to it.

When the odd number becomes greater than or equal to m, we count the number of subarrays formed until the index and "odd - m" numbers are added to the count variable. After each element is processed, the result is stored in the count variable.

Example

#include <bits/stdc++.h>
using namespace std;
int main (){
    int array[ ] = { 1, 6, 3, 2, 5, 4 };
    int n = 6, m = 2, count = 0, odd = 0, i;
    int prefix_array[n + 1] = { 0 };
    // outer loop to process every element of array
    for (i = 0; i < n; i++){
        prefix_array[odd] = prefix_array[odd] + 1;    // implementing value at odd index in prefix_array[ ]
        // if array element is odd then increment odd variable
        if (array[i] % 2 == 0)
            odd++;
        // if Number of odd element becomes equal or greater than m
        //  then find the number of possible subarrays that can be formed till the index.
        if (odd >= m)
            count += prefix_array[odd - m];
    }
    cout << "Number of subarrays with n numbers are: " << count;
    return 0;
}
Copy after login

Output

Number of subarrays with n numbers are: 6
Copy after login
Copy after login

Explanation of the above code

Initialize arrays and variables with starting values ​​-

int array[ 6 ] = { 1, 6, 3, 2, 5, 4 };
int n = 6, m = 2, count = 0, odd = 0, i;
int prefix_array[n + 1] = { 0 };
Copy after login

Here , we initialize the variable n with the size of the array, m with the number of odd numbers to find, the count with 0 to keep a count of possible subarrays, the odd numbers with 0, and the variable n 0 with a prefix_array of size n 1 .

Understanding Loops

for (i = 0; i < n; i++){
   prefix_array[odd] = prefix_array[odd] + 1;
   if (array[i] % 2 == 0)
      odd++;
      if (odd >= m)
         count += prefix_array[odd - m];
}
Copy after login

In this loop we implement the value at odd index in prefix_array[] and then increment the odd variable if an odd number is found. We find that when odd variables are equal to or greater than m, the number of subarrays can be formed, up to index.

Finally, we print the m odd subarray numbers stored in the count variable and get the output.

Conclusion

In this article, we learned about the method of finding the number of m odd subarrays through two methods-

  • Generate each sub-array array and check if there are m odd numbers in it and increment the count for each sub-array found. The time complexity of this code is O(n2).

  • Efficient way, iterate through each element of the array and create a prefix array, then use the help of prefix array. The time complexity of this code is O(n).

Hope this article helps you understand the problem and solution.

The above is the detailed content of Programming in C++, find the number of subarrays with m odd numbers. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Use C++ to write code to find the Nth non-square number Use C++ to write code to find the Nth non-square number Aug 30, 2023 pm 10:41 PM

We all know numbers that are not the square of any number, such as 2, 3, 5, 7, 8, etc. There are N non-square numbers, and it is impossible to know every number. So, in this article, we will explain everything about squareless or non-square numbers and ways to find the Nth non-square number in C++. Nth non-square number If a number is the square of an integer, then the number is called a perfect square. Some examples of perfect square numbers are -1issquareof14issquareof29issquareof316issquareof425issquareof5 If a number is not the square of any integer, then the number is called non-square. For example, the first 15 non-square numbers are -2,3,5,6,

In C programming, find the area of ​​a circle In C programming, find the area of ​​a circle Aug 25, 2023 pm 10:57 PM

A circle is a closed figure. All points on a circle are equidistant from a point inside the circle. The center point is called the center of the circle. The distance from a point to the center of a circle is called the radius. Area is a quantitative representation of the span of dimensions of a closed figure. The area of ​​a circle is the area enclosed within the dimensions of the circle. The formula to calculate the area of ​​a circle, Area=π*r*r To calculate the area, we give the radius of the circle as input, we will use the formula to calculate the area, algorithm STEP1: Takeradiusasinputfromtheuserusingstdinput.STEP2: Calculatetheareaofcircleusing, area=(

Find the number of unique pairs in an array using C++ Find the number of unique pairs in an array using C++ Sep 07, 2023 am 11:53 AM

We need proper knowledge to create several unique pairs in array syntax of C++. While finding the number of unique pairs, we count all the unique pairs in the given array i.e. all possible pairs can be formed where each pair should be unique. For example -Input:array[]={5,5,9}Output:4Explanation:Thenumberoffalluniquepairsare(5,5),(5,9),(9,5)and(9,9).Input:array[]= {5,4,3,2,2}Output:16 Ways to Find Solution There are two ways to solve this problem, they are −

Inversion algorithm for right rotation of array written in C++ Inversion algorithm for right rotation of array written in C++ Sep 08, 2023 pm 08:17 PM

In this article, we will learn about the reversal algorithm to rotate a given array to the right by k elements, for example −Input:arr[]={4,6,2,6,43,7,3,7},k= 4Output:{43,7,3,7,4,6,2,6}Explanation:Rotatingeachelementofarrayby4-elementtotherightgives{43,7,3,7,4,6,2,6}.Input:arr[]={8 ,5,8,2,1,4,9,3},k=3Output:{4,9,3,8,5,8,2,1} Find the solution

Write a code using C++ to find the number of subarrays with the same minimum and maximum values Write a code using C++ to find the number of subarrays with the same minimum and maximum values Aug 25, 2023 pm 11:33 PM

In this article, we will use C++ to solve the problem of finding the number of subarrays whose maximum and minimum values ​​are the same. The following is an example of the problem −Input:array={2,3,6,6,2,4,4,4}Output:12Explanation:{2},{3},{6},{6},{2 },{4},{4},{4},{6,6},{4,4},{4,4}and{4,4,4}arethesubarrayswhichcanbeformedwithmaximumandminimumelementsame.Input:array={3,3, 1,5,

Reverse doubly linked list grouping by given size using C++ Reverse doubly linked list grouping by given size using C++ Sep 04, 2023 am 09:49 AM

In this problem, we are given a pointer to the head of the linked list and an integer k. In a group of size k, we need to reverse the linked list. For example -Input:1<->2<->3<->4<->5(doublylinkedlist),k=3Output:3<->2<->1<->5<->4 looking for solutions Method In this problem, we will formulate a recursive algorithm to solve this problem. In this method we will use recursion and solve the problem using recursion. Example#include<iostream&

Reversal algorithm for array rotation written in C++ Reversal algorithm for array rotation written in C++ Aug 28, 2023 pm 11:13 PM

In the given problem, we have an array and we need to rotate the array by d elements using inversion algorithm like −Input:arr[]=[1,2,3,4,5,6,7], d=2Output:arr[]=[3,4,5,6,7,1,2]Explanation:Asyoucanseewehavetorotatethisarraybyd=2butourmaintaskistoachievethisbyusingareversaltechnique. We performed some inversion technique calculations on the rotation of the array and concluded: First, we reverse

Written in C++, find the number of reflexive relations on a set Written in C++, find the number of reflexive relations on a set Aug 26, 2023 pm 08:17 PM

In this article we will explain ways to find reflexive relations on a set. In this problem, we are given a number n, and a set of n natural numbers, and we must determine the number of reflexive relations. Reflexive relation - A relation R is said to be a reflexive relation on the set A if for every 'a' in the set A, (a, a) belongs to the relation R. For example -Input:x=1Output:1Explanation:set={1},reflexiverelationsonA*A:{{1}}Input:x=2Output:4Explanation:set={1,2},reflexiverelationsonA*

See all articles