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
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; }
Output
Number of subarrays with odd sum : 9
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; }
Output
Number of subarrays with odd sum : 9
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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 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,

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

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

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,

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<bits/stdc++.h>usingnamespacestd;structNode{//s
