-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathcp1.cpp
74 lines (57 loc) · 1.46 KB
/
cp1.cpp
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
69
70
71
72
73
74
// CPP program to find number of subarrays having
// sum in the range L to R.
#include <bits/stdc++.h>
using namespace std;
// Function to find number of subarrays having
// sum less than or equal to x.
int countSub(int arr[], int n, int x)
{
// Starting index of sliding window.
int st = 0;
// Ending index of sliding window.
int end = 0;
// Sum of elements currently present
// in sliding window.
int sum = 0;
// To store required number of subarrays.
int cnt = 0;
// Increment ending index of sliding
// window one step at a time.
while (end < n) {
// Update sum of sliding window on
// adding a new element.
sum += arr[end];
// Increment starting index of sliding
// window until sum is greater than x.
while (st <= end && sum > x) {
sum -= arr[st];
st++;
}
// Update count of number of subarrays.
cnt += (end - st + 1);
end++;
}
return cnt;
}
// Function to find number of subarrays having
// sum in the range L to R.
int findSubSumLtoR(int arr[], int n, int L, int R)
{
// Number of subarrays having sum less
// than or equal to R.
int Rcnt = countSub(arr, n, R);
// Number of subarrays having sum less
// than or equal to L-1.
int Lcnt = countSub(arr, n, L - 1);
return Rcnt - Lcnt;
}
// Driver code.
int main()
{
int arr[] = { 1, 4, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
int L = 3;
int R = 8;
cout << findSubSumLtoR(arr, n, L, R);
return 0;
}