Skip to content

Commit 6be6ee7

Browse files
Create Subarrays.cpp
1 parent 6a00544 commit 6be6ee7

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

Subarrays.cpp

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/*C++ program to find total number of
2+
even-odd subarrays present in given array*/
3+
#include <bits/stdc++.h>
4+
using namespace std;
5+
6+
// function that returns the count of subarrays that
7+
// contain equal number of odd as well as even numbers
8+
int countSubarrays(int arr[], int n)
9+
{
10+
// initialize difference and answer with 0
11+
int difference = 0;
12+
int ans = 0;
13+
14+
// create two auxiliary hash arrays to count frequency
15+
// of difference, one array for non-negative difference
16+
// and other array for negative difference. Size of these
17+
// two auxiliary arrays is 'n+1' because difference can
18+
// reach maximum value 'n' as well as minimum value '-n'
19+
int hash_positive[n + 1], hash_negative[n + 1];
20+
21+
// initialize these auxiliary arrays with 0
22+
fill_n(hash_positive, n + 1, 0);
23+
fill_n(hash_negative, n + 1, 0);
24+
25+
// since the difference is initially 0, we have to
26+
// initialize hash_positive[0] with 1
27+
hash_positive[0] = 1;
28+
29+
// for loop to iterate through whole
30+
// array (zero-based indexing is used)
31+
for (int i = 0; i < n ; i++)
32+
{
33+
// incrementing or decrementing difference based on
34+
// arr[i] being even or odd, check if arr[i] is odd
35+
if (arr[i] & 1 == 1)
36+
difference++;
37+
else
38+
difference--;
39+
40+
// adding hash value of 'difference' to our answer
41+
// as all the previous occurrences of the same
42+
// difference value will make even-odd subarray
43+
// ending at index 'i'. After that, we will increment
44+
// hash array for that 'difference' value for
45+
// its occurrence at index 'i'. if difference is
46+
// negative then use hash_negative
47+
if (difference < 0)
48+
{
49+
ans += hash_negative[-difference];
50+
hash_negative[-difference]++;
51+
}
52+
53+
// else use hash_positive
54+
else
55+
{
56+
ans += hash_positive[difference];
57+
hash_positive[difference]++;
58+
}
59+
}
60+
61+
// return total number of even-odd subarrays
62+
return ans;
63+
}
64+
65+
// Driver code
66+
int main()
67+
{
68+
int arr[] = {3, 4, 6, 8, 1, 10, 5, 7};
69+
int n = sizeof(arr) / sizeof(arr[0]);
70+
71+
// Printing total number of even-odd subarrays
72+
cout << "Total Number of Even-Odd subarrays"
73+
" are " << countSubarrays(arr,n);
74+
75+
return 0;
76+
}

0 commit comments

Comments
 (0)