Table of Contents
brute force method
Example
Output
Description of the above code
Efficient method
Explanation of the above code
Conclusion
Home Backend Development C++ Write a code using C++ to find the number of subarrays with odd sums

Write a code using C++ to find the number of subarrays with odd sums

Sep 21, 2023 am 08:45 AM
quantity subarray Odd sums

Write a code using C++ to find the number of subarrays with odd sums

A subarray is a contiguous part of an array. For example, we consider an array [5, 6, 7, 8], then there are ten non-empty sub-arrays, such as (5), (6), (7), (8), (5, 6), (6, 7), (7,8), (5,6,7), (6,7,8) and (5,6,7,8).

In this guide, we will explain all possible information in C to find the number of subarrays with odd sums. To find the number of sub-arrays of odd sums we can use different methods so here is a simple example -

Input : array = {9,8,7,6,5}
Output : 9

Explanation :
Sum of subarray -
{9} = 9
{7} = 7
{5} = 5
{9,8} = 17
{8,7} = 15
{7,6} = 13
{6,5} = 11
{8,7,6} = 21
{9,8,7,6,5} = 35
Copy after login

brute force method

By this method we can simply check Is the sum of elements in all sub-arrays even or odd, if it is even we will reject that sub-array and count the sub-array whose sum is odd, this is not an efficient way as the complexity of this code is O(n2).

Example

#include <bits/stdc++.h>
using namespace std;
int main(){
    int n=5, temp = 0;
    int a[n-1] = { 9,8,7,6,5 } ; // declaring our array.
    int cnt = 0; // counter variable.
    for(int i = 0; i < n; i++){
        temp = 0; // refreshing our temp sum.
        for(int j = i; j < n; j++){ // this loop will make our subarrays starting from i till n-1.
            temp = temp + a[j];
            if( temp % 2 == 1 )
                cnt++;
        }
    }
    cout << "Number of subarrays with odd sum : " << cnt << "\n";
    return 0;
}
Copy after login

Output

Number of subarrays with odd sum : 9
Copy after login
Copy after login

Description of the above code

A nested loop is used in this code, where the outer loop is used to increment the value of I , I points to each value from the beginning of the array; the inner loop is used to find the subarray starting at position " i " with an odd sum.

Efficient method

In this method we are processing every element starting from the 0th position in the array. If the current element is odd, increment an odd counter and increment an even counter for each even number. If we find an odd number, the values ​​of Even and odd are swapped, since adding an odd number to the subarray changes its parity, and finally a count is added to the result. The complexity of this code is O(n) since we are processing each element.

Example

 
#include <bits/stdc++.h>
using namespace std;
int main(){
    int odd = 0, even = 0,  result = 0,n=5,i,temp;
    int arr[ n-1 ] = { 9,8,7,6,5}; // initialising the array
     // for loop for processing every element of array
    for ( i = 0 ; i < n ; i ++ )  {
        if ( arr[ i ] % 2 == 0 ) {
            even++;
        } else {
          // swapping even odd values
            temp = even;
            even = odd;
            odd = temp + 1;
        }
        result += odd;
    }
    cout << "Number of subarrays with odd sum : " << result;
}
Copy after login

Output

Number of subarrays with odd sum : 9
Copy after login
Copy after login

Explanation of the above code

In this code, we check the even/odd number of each element and Increment the even counter for even numbers and increment the odd counter for odd numbers. Additionally, if an odd number is found, we will swap the parity counter values; otherwise, it will change the parity of the subarray. Then add the value of the odd counter to the result variable after each iteration.

Conclusion

In this article we explained how to find the number coercion method from Brute for subarrays with an odd sum, generate each subarray with an odd sum and increment the count. The time complexity of this code is O(n2). An efficient way to do this is to iterate over each element of the array and increment the odd/even counter variable with each odd/even number found, swapping the counters if an odd number is found; the time complexity of this code is O(n). I hope you found this article helpful in understanding the problem and solution.

The above is the detailed content of Write a code using C++ to find the number of subarrays with odd sums. 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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
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)

OpenOOD update v1.5: Comprehensive and accurate out-of-distribution detection code library and testing platform, supporting online rankings and one-click testing OpenOOD update v1.5: Comprehensive and accurate out-of-distribution detection code library and testing platform, supporting online rankings and one-click testing Jul 03, 2023 pm 04:41 PM

Out-of-distribution (OOD) detection is crucial for the reliable operation of open-world intelligent systems, but current object-oriented detection methods suffer from "evaluation inconsistencies" (evaluation inconsistencies). Previous work OpenOODv1 unifies the evaluation of OOD detection, but still has limitations in scalability and usability. Recently, the development team once again proposed OpenOODv1.5. Compared with the previous version, the new OOD detection method evaluation has been significantly improved in ensuring accuracy, standardization and user-friendliness. Image Paper: https://arxiv.org/abs/2306.09301OpenOODCodebase:htt

Increase your knowledge! Machine learning with logical rules Increase your knowledge! Machine learning with logical rules Apr 01, 2023 pm 10:07 PM

On the precision-recall curve, the same points are plotted with different axes. Warning: The first red dot on the left (0% recall, 100% precision) corresponds to 0 rules. The second dot on the left is the first rule, and so on. Skope-rules uses a tree model to generate rule candidates. First build some decision trees and consider the paths from the root node to internal nodes or leaf nodes as rule candidates. These candidate rules are then filtered by some predefined criteria such as precision and recall. Only those with precision and recall above their thresholds are retained. Finally, similarity filtering is applied to select rules with sufficient diversity. In general, Skope-rules are applied to learn the root cause of each

How to find the number of parameters provided by runtime in Java? How to find the number of parameters provided by runtime in Java? Sep 23, 2023 pm 01:13 PM

In Java, one way to pass parameters at runtime is to use the command line or terminal. When retrieving these values ​​for command line parameters, we may need to find the number of parameters provided by the user at runtime, which can be achieved with the help of the length attribute. This article aims to explain the process of passing and getting a user-supplied number of parameters with the help of a sample program. Get the number of arguments provided by the user at run time Before finding the number of command line arguments, our first step is to create a program that allows the user to pass arguments at run time. String[] parameter When writing Java programs, we often encounter the main() method. When the JVM calls this method, the Java application starts executing. It is used with an argument called String[]args

Linux command: How to check the number of telnet processes Linux command: How to check the number of telnet processes Mar 01, 2024 am 11:39 AM

Linux commands are one of the indispensable tools in the daily work of system administrators. They can help us complete various system management tasks. In operation and maintenance work, sometimes it is necessary to check the number of a certain process in the system in order to detect problems and make adjustments in time. This article will introduce how to use Linux commands to check the number of telnet processes, let us learn together. In Linux systems, we can use the ps command combined with the grep command to view the number of telnet processes. First, we need to open a terminal,

In Java, find the maximum subarray sum of subarrays after splitting an array into subarrays based on a given query In Java, find the maximum subarray sum of subarrays after splitting an array into subarrays based on a given query Aug 29, 2023 am 11:21 AM

We have two arrays of integers, one with the calculated elements and the other with the split points required to split the array to generate subsets, we have to calculate the sum of each subset in each split and return the maximum subset Let's go through the example Understanding: - input −intarr[]=intarr[]={9,4,5,6,7}intsplitPoints[]={0,2,3,1}; output−the maximum subarray sum after each split [ 22,13,9,9] Explanation − Here we decompose the array according to its split points and get the maximum subset after each split and after the first split → {9} and {4,5,6,7 }>>The maximum sum of subarrays is -22 after the second split→{9},{4

C++ program to calculate the sum of all odd numbers between 1 and N C++ program to calculate the sum of all odd numbers between 1 and N Sep 06, 2023 pm 08:05 PM

Obtaining the sum of a series is one of the simplest practice tasks when we learn programming and logic construction. In mathematics, there are ways to find the sum of series present in different series. In programming we generate them one by one by implementing logic and add them repeatedly to get the sum or else do anything else as required. In this article, we will introduce the technique of getting the sum of all odd numbers up to N using C++. There are two possible ways to get this sum, but with a little twist. Let’s look at these methods one by one. The algorithm is capped at the number N. Initialize the sum to 0. i ranges from 1 to N. If i is an odd number, then. Sum:=sum+i. If it ends. Display the sum. Example#include<iostre

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,

Find the number of ways to traverse an N-ary tree using C++ Find the number of ways to traverse an N-ary tree using C++ Sep 04, 2023 pm 05:01 PM

Given an N-ary tree, our task is to find the total number of ways to traverse the tree, e.g. − For the tree above, our output will be 192. For this problem, we need some knowledge of combinatorics. Now in this problem we just need to check all possible combinations of each path and this will give us the answer. Method to find the solution In this method we just need to perform a hierarchy traversal, check how many children each node has, and then factorially multiply it with the answer. Example C++ code of the above method #include&lt;bits/stdc++.h&gt;usingnamespacestd;structNode{//s

See all articles