Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive.
Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j (i ≤ j), inclusive.
Note:
A naive algorithm of O(n2) is trivial. You MUST do better than that.
Example:
Input: nums = [-2,5,-1], lower = -2, upper = 2,
Output: 3
Explanation: The three ranges are : [0,0], [2,2], [0,2] and their respective sums are: -2, -1, 2.
Firstly, we calculate the littlesum[i], which means the sum of the elements from index 0 to index i.
Based on above operations, we can get the sum S[i, j] of elements in the range [i, j] by littlesum[j] - littlesum[i - 1].
Now we want to get the count of (i, j) which make lower <= S[i, j] <= upper.
The naive solution we can think of is a O(n^2) solution, we get thought all pair of i and j, then compare S[i, j] with lower and upper.
But the question tell us we must do beter than that.
Here is a interesting solution using STL.
Put all the elements of littlesum into a multiset and they will be sorted automatically, then we pass through the set, for every element A, we find lower_bound(A - upper) and A - lower.
int countRangeSum(vector<int>& nums, int lower, int upper)
{
int result = 0;
long long sum = 0;
multiset<long long> st;
/*
Firstly, we insert 0 into st, it means itself, for example, we are dealing this situation where sum = 3 and i = 5,
and the lower is 2, the upper is 4, it's clear that the range [0, 5] is one of the right answers, and we can't get it by littlesum[i] - littlesum[j] (i >= 0, j >= 0) except littlesum[j] equals 0.
so, we insert 0 into st firstly, sum with index i minus 0 means sum itself.
*/
st.insert(0);
//In case of duplicate addition of result, we do distance() once we put sum into the st, which means we just choose appropriate littesum[j] whose j is smaller than or same as i.
for(int i = 0; i < nums.size(); i++)
{
sum += nums[i];
//And the range of [i, j] is at least 1, so we insert sum into st after distance().
result += distance(st.lower_bound(sum - upper), st.upper_bound(sum - lower));
st.insert(sum);
}
return result;
}