Given an positive integer array A
and an interval. Return the number of subarrays whose sum is in the range of given interval.
Example
Example 1:
Input: A = [1, 2, 3, 4], start = 1, end = 3
Output: 4
Explanation: All possible subarrays: [1](sum = 1), [1, 2](sum = 3), [2](sum = 2), [3](sum = 3).
Example 2:
Input: A = [1, 2, 3, 4], start = 1, end = 100
Output: 10
Explanation: Any subarray is ok.
Notice
Subarray is a part of origin array with continuous index.
思路:固定右边界aj, 问题转换为找左边的两个边界,
XXXVVVVVVVVXXXXX aj
.....ai .................ak ........ aj
<=end >=start
这两个区间都是可以用双指针来计算得到的,O(N)
Prefix Sum 现在用n+1数组来求;
public class Solution {
/**
* @param A: An integer array
* @param start: An integer
* @param end: An integer
* @return: the number of possible answer
*/
public int subarraySumII(int[] A, int start, int end) {
if(A == null || A.length == 0) {
return 0;
}
int n = A.length;
int[] prefixSum = new int[n + 1];
prefixSum[0] = 0;
for(int i = 1; i <= n; i++) {
prefixSum[i] = prefixSum[i - 1] + A[i - 1];
}
int res = 0;
/**
XXXXXXVVVVVVVVVXXXXXX j
>end <start
left right
*/
int left = 0, right = 0;
for(int j = 1; j <= n; j++) {
while(right < j && prefixSum[j] - prefixSum[right] >= start) {
right++;
}
while(left < j && prefixSum[j] - prefixSum[left] > end) {
left++;
}
res += (right - left);
}
return res;
}
}