-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1248_Count_Number_of_Nice_Subarrays.cpp
More file actions
61 lines (61 loc) · 1.49 KB
/
1248_Count_Number_of_Nice_Subarrays.cpp
File metadata and controls
61 lines (61 loc) · 1.49 KB
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
/*
1248. Count Number of Nice Subarrays
Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.
Return the number of nice sub-arrays.
Example 1:
Input: nums = [1,1,2,1,1], k = 3
Output: 2
Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].
Example 2:
Input: nums = [2,4,6], k = 1
Output: 0
Explanation: There are no odd numbers in the array.
Example 3:
Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2
Output: 16
Constraints:
1 <= nums.length <= 50000
1 <= nums[i] <= 10^5
1 <= k <= nums.length
*/
/*
OPTIMIZED APPROACH (Prefix / Sliding Window / Hash Table)
Time Complexity o(n);
Space Complexity o(n);
*/
class Solution {
public:
int numberOfSubarrays(vector<int>& nums, int k) {
int n = nums.size();
vector<int> cnt(n + 1, 0);
cnt[0] = 1;
int ans = 0, t = 0;
for (int v : nums) {
t += v & 1;
if (t - k >= 0) {
ans += cnt[t - k];
}
cnt[t]++;
}
return ans;
}
};
/*
NOT OPTIMIZED APPROACH (TIME LIMIT EXCEED ERROR)
Time Complexity o(n^2);
Space Complexity o(1);
*/
class Solution {
public:
int numberOfSubarrays(vector<int>& nums, int k) {
int count =0 ;
for(int i = 0 ; i<nums.size();i++){
int oddCount = 0 ;
for(int j = i;j<nums.size();j++){
if(nums[j]&1) oddCount++;
if(oddCount==k) count++;
}
}
return count ;
}
};