-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArray_MaxNiceSybarray_k.cpp
More file actions
68 lines (51 loc) · 1.63 KB
/
Array_MaxNiceSybarray_k.cpp
File metadata and controls
68 lines (51 loc) · 1.63 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
62
63
64
65
66
67
68
//exactly same as previous question the only changes has been mark in the code abhi.
#include <iostream>
#include <vector>
using namespace std;
int numSubarraysWithSum(vector<int>& nums, int k) {
int l = 0;
int r = 0;
int count = 0;
int sum = 0;
while (r < nums.size()) {
sum = sum + nums[r]%2; //added %2 this will either give 0 or 1
while (sum > k) {
sum = sum - nums[l]%2; //added %2 this will either give 0 or 1
l++;
}
if (sum <= k) {
count = count + r - l + 1;
}
r++;
}
int kLessThanOne(vector<int>& nums, int k);
// calling the function (k-1)
int kessOne = kLessThanOne(nums, k - 1);
int originalk = count - kessOne;
return originalk;
}
int kLessThanOne(vector<int>& nums, int k) {
if (k < 0) return 0;
int l = 0;
int r = 0;
int count = 0;
int sum = 0;
while (r < nums.size()) {
sum = sum + nums[r]%2; //added %2 this will either give 0 or 1
while (sum > k) {
sum = sum - nums[l]%2; //added %2 this will either give 0 or 1
l++;
}
if (sum <= k) {
count = count + r - l + 1;
}
r++;
}
return count;
}
int main() {
vector<int> nums = {2,2,2,1,2,2,1,2,2,2};
int k = 2;
cout<<numSubarraysWithSum(nums,k);
return 0;
}