-
Notifications
You must be signed in to change notification settings - Fork 0
/
Subarray Sum II.cpp
36 lines (36 loc) · 955 Bytes
/
Subarray Sum II.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
class Solution {
public:
/**
* @param A an integer array
* @param start an integer
* @param end an integer
* @return the number of possible answer
*/
int subarraySumII(vector<int>& A, int start, int end) {
// Write your code here
int n = A.size();
if(n == 0) return 0;
int i = 0, j = 1, k = 1;
int sumi = 0, sumj = A[0], sumk = A[0];
int ans = 0;
while(i < n) {
if(j <= n && sumj-sumi < start) {
if(j < n)
sumj += A[j];
j++;
}
else if(k <= n && sumk-sumi <= end) {
if(k < n)
sumk += A[k];
k++;
}
else {
ans += k-j;
sumi += A[i++];
if(i == j) sumj += A[j++];
if(i == k) sumk += A[k++];
}
}
return ans;
}
};