[LeetCode] Sum of Consecutive Subarrays

3284. Sum of Consecutive Subarrays

We call an array arr of length n consecutive if one of the following holds:

  • arr[i] - arr[i - 1] == 1 for all 1 <= i < n.
  • arr[i] - arr[i - 1] == -1 for all 1 <= i < n.

The value of an array is the sum of its elements.

For example, [3, 4, 5] is a consecutive array of value 12 and [9, 8] is another of value 17. While [3, 4, 3] and [8, 6] are not consecutive.

Given an array of integers nums, return the sum of the values of all consecutive subarrays.

Since the answer may be very large, return it modulo 109 + 7.

Note that an array of length 1 is also considered consecutive.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

class Solution {
public:
int getSum(vector<int>& nums) {
long long n = nums.size(), mod = 1e9 + 7, res = 0;
auto calc = [&](int l, int r) {
long long pre = 0, cnt = 0;
for(int i = l; i <= r; i++) {
++cnt;
pre = (pre + cnt * nums[i] % mod) % mod;
res = (res + pre) % mod;
}
};
int i = 0;
while(i < n) {
int j = i + 1;
if(j == n or abs(nums[i] - nums[j]) != 1) {
res = (res + nums[i]) % mod;
i++;
} else {
int diff = nums[i] - nums[j];
while(j < n and nums[j-1] - nums[j] == diff) j++;
calc(i,j-1);
if(j < n and abs(nums[j-1] - nums[j]) == 1) {
res -= nums[j-1];
i = j - 1;
} else i = j;
}
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2025/11/21/PS/LeetCode/sum-of-consecutive-subarrays/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.