GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Create 1248_count_number_of_nice_sub_arrays.cpp (#31) · manondidi/leetcode@bafd820

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • cpp
    • 1248_count_number_of_nice_sub_arrays.cpp
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎cpp/1248_count_number_of_nice_sub_arrays.cpp‎

Copy file name to clipboard
+42Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution {
2+
public:
3+
int numberOfSubarrays(vector<int>& nums, int k) {
4+
return atMostK(nums, k) - atMostK(nums, k - 1);
5+
}
6+
7+
private:
8+
int atMostK(const vector<int>& nums, int k) {
9+
int result = 0, left = 0, count = 0;
10+
for (int right = 0; right < nums.size(); ++right) {
11+
count += nums[right] % 2;
12+
while (count > k) {
13+
count -= nums[left] % 2;
14+
++left;
15+
}
16+
result += right - left + 1;
17+
}
18+
return result;
19+
}
20+
};
21+
22+
// Time: O(n)
23+
// Space: O(k)
24+
class Solution2 {
25+
public:
26+
int numberOfSubarrays(vector<int>& nums, int k) {
27+
int result = 0;
28+
deque<int> dq = {-1};
29+
for (int i = 0; i < nums.size(); ++i) {
30+
if (nums[i] % 2) {
31+
dq.emplace_back(i);
32+
}
33+
if (dq.size() > k + 1) {
34+
dq.pop_front();
35+
}
36+
if (dq.size() == k + 1) {
37+
result += dq[1] - dq[0];
38+
}
39+
}
40+
return result;
41+
}
42+
};

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.