1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Solution { public: int numSubarraysWithSum(vector<int>& nums, int goal) { int ans = 0; for (int l1 = 0, l2 = 0, sum1 = 0, sum2 = 0, r = 0; r < nums.size(); ++r) { sum1 += nums[r]; sum2 += nums[r]; while (sum1 > goal) sum1 -= nums[l1++]; while (l2 <= r && sum2 >= goal) sum2 -= nums[l2++]; ans += l2 - l1; } return ans; } };
|