Skip to content

Commit c153856

Browse files
authored
Create sum-of-consecutive-subarrays.cpp
1 parent 07900a1 commit c153856

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

C++/sum-of-consecutive-subarrays.cpp

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
// combinatorics
5+
class Solution {
6+
public:
7+
int getSum(vector<int>& nums) {
8+
static const int MOD = 1e9 + 7;
9+
const auto& count = [&](int d) {
10+
int64_t result = 0, total = 0, cnt = 0;
11+
for (int i = 0; i < size(nums); ++i) {
12+
total = (total + ++cnt * nums[i]) % MOD;
13+
result = (result + total) % MOD;
14+
if (i + 1 < size(nums) && nums[i + 1] - nums[i] == d) {
15+
continue;
16+
}
17+
total = cnt = 0;
18+
}
19+
return result;
20+
};
21+
22+
return (count(1) + count(-1) - accumulate(cbegin(nums), cend(nums), 0ll, [](const auto& a, const auto& b) {
23+
return (a + b) % MOD;
24+
})) % MOD;
25+
}
26+
};

0 commit comments

Comments
 (0)