-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCount-Number-Of-Nice-Subarrays.cpp
92 lines (89 loc) · 2.52 KB
/
Count-Number-Of-Nice-Subarrays.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Leetcode 1248 (Nice Problem)
class Solution
{
public:
int numberOfSubarrays(vector<int> &nums, int k)
{
int n = nums.size();
int i = 0, j = 0;
int countOfOddInCurrentWindow = 0;
int totalInCurrentWindow = 0;
int totalAllOver = 0;
while (j < n)
{
int el = nums[j];
if (el & 1)
{
countOfOddInCurrentWindow++;
// we make current window count to 0, since new formation will take place
totalInCurrentWindow = 0;
}
if (countOfOddInCurrentWindow < k)
{
j++;
}
else if (countOfOddInCurrentWindow == k)
{
while (countOfOddInCurrentWindow == k)
{
totalInCurrentWindow++;
if (nums[i] & 1)
{
countOfOddInCurrentWindow--;
}
i++;
}
j++;
}
// totalInCurrentWindow if not 0, gets added all over, since in previous window all
// conditions were satisfied now if we add some even to it, condition does not
// change so previous count gets added again --> think once
totalAllOver += totalInCurrentWindow;
}
return totalAllOver;
}
};
// [Note: Can be solved with approach similar to Leetcode 992]
class Solution
{
public:
int solve(vector<int> &nums, int k)
{
int n = nums.size();
int i = 0, j = 0;
int countOfOddInCurrentWindow = 0;
int totalAllOver = 0;
while (j < n)
{
int el = nums[j];
if (el & 1)
{
countOfOddInCurrentWindow++;
}
if (countOfOddInCurrentWindow <= k)
{
// count of 1 to k
totalAllOver += j - i + 1;
j++;
}
else if (countOfOddInCurrentWindow > k)
{
while (countOfOddInCurrentWindow > k)
{
if (nums[i] & 1)
{
countOfOddInCurrentWindow--;
}
i++;
}
totalAllOver += j - i + 1;
j++;
}
}
return totalAllOver;
}
int numberOfSubarrays(vector<int> &nums, int k)
{
return solve(nums, k) - solve(nums, k - 1);
}
};