File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time: O(n)
2
+ // Space: O(k)
3
+
4
+ class Solution {
5
+ public:
6
+ int numberOfSubarrays (vector<int >& nums, int k) {
7
+ return atMostK (nums, k) - atMostK (nums, k - 1 );
8
+ }
9
+
10
+ private:
11
+ int atMostK (const vector<int >& nums, int k) {
12
+ int result = 0 , left = 0 , count = 0 ;
13
+ for (int right = 0 ; right < nums.size (); ++right) {
14
+ count += nums[right] % 2 ;
15
+ while (count > k) {
16
+ count -= nums[left] % 2 ;
17
+ ++left;
18
+ }
19
+ result += right - left + 1 ;
20
+ }
21
+ return result;
22
+ }
23
+ };
24
+
25
+ // Time: O(n)
26
+ // Space: O(k)
27
+ class Solution2 {
28
+ public:
29
+ int numberOfSubarrays (vector<int >& nums, int k) {
30
+ int result = 0 ;
31
+ deque<int > dq = {-1 };
32
+ for (int i = 0 ; i < nums.size (); ++i) {
33
+ if (nums[i] % 2 ) {
34
+ dq.emplace_back (i);
35
+ }
36
+ if (dq.size () > k + 1 ) {
37
+ dq.pop_front ();
38
+ }
39
+ if (dq.size () == k + 1 ) {
40
+ result += dq[1 ] - dq[0 ];
41
+ }
42
+ }
43
+ return result;
44
+ }
45
+ };
You can’t perform that action at this time.
0 commit comments