-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArray_BinarySubarrayWithSum.cpp
More file actions
68 lines (53 loc) · 1.53 KB
/
Array_BinarySubarrayWithSum.cpp
File metadata and controls
68 lines (53 loc) · 1.53 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
/* In this question the r goes out of bound while traversing for the possible solutions thats why
we first find all subarrays with sum<=goal and substracted it with same type of function where sum==goal-1 */
#include <iostream>
#include <vector>
using namespace std;
int numSubarraysWithSum(vector<int>& nums, int goal) {
int l = 0;
int r = 0;
int count = 0;
int sum = 0;
while (r < nums.size()) {
sum = sum + nums[r];
while (sum > goal) {
sum = sum - nums[l];
l++;
}
if (sum <= goal) {
count = count + r - l + 1;
}
r++;
}
int goalLessThanOne(vector<int>& nums, int goal);
// calling the function (goal-1)
int goalessOne = goalLessThanOne(nums, goal - 1);
int originalGoal = count - goalessOne;
return originalGoal;
}
int goalLessThanOne(vector<int>& nums, int goal) {
if (goal < 0) return 0;
int l = 0;
int r = 0;
int count = 0;
int sum = 0;
while (r < nums.size()) {
sum = sum + nums[r];
while (sum > goal) {
sum = sum - nums[l];
l++;
}
if (sum <= goal) {
count = count + r - l + 1;
}
r++;
}
return count;
}
int main() {
// Example input
vector<int> nums = {1, 0, 1, 0, 1};
int goal = 2;
cout<<numSubarraysWithSum(nums,goal);
return 0;
}