Sliding window doesn't work. So it is a typical partial_sum base solution. As below. However if you use a balanced binary search tree, you can get O(nlgn) - like std::set<int>
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
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) { size_t len = A.size(); vector<int> presum(len + 1); std::partial_sum(A.begin(), A.end(), presum.begin() + 1); int ret = 0; for(int i = 1; i <= len; i ++) { for(int j = 0; j < i; j++) { int diff = presum[i] - presum[j]; if(diff<=end && diff>=start) ret ++; } } return ret; } };