- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 50 lines of C++ from the credited upstream file 1508.cpp.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int rangeSum(vector<int>& nums, int n, int left, int right) {4 constexpr int kMod = 1'000'000'007;5 6 auto subarraysAndSumNoGreaterThan = [&](int m) -> pair<int, long> {7 int count = 0; 8 long total = 0; 9 int sum = 0; 10 int window = 0; 11 12 for (int i = 0, j = 0; j < n; ++j) {13 sum += nums[j] * (j - i + 1);14 window += nums[j]; 15 while (window > m) {16 sum -= window;17 window -= nums[i++]; 18 }19 count += j - i + 1;20 total += sum;21 }22 23 return {count, total};24 };25 26 27 const int L = ranges::min(nums);28 const int R = accumulate(nums.begin(), nums.end(), 0);29 30 auto firstKSubarraysSum = [&](int k) -> long {31 int l = L;32 int r = R;33 34 while (l < r) {35 const int m = l + (r - l) / 2;36 if (subarraysAndSumNoGreaterThan(m).first < k)37 l = m + 1;38 else39 r = m;40 }41 42 const auto& [count, total] = subarraysAndSumNoGreaterThan(l);43 44 return total - l * (count - k);45 };46 47 return (firstKSubarraysSum(right) - firstKSubarraysSum(left - 1)) % kMod;48 }49};50