-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path3351.cpp
More file actions
39 lines (33 loc) · 1.09 KB
/
3351.cpp
File metadata and controls
39 lines (33 loc) · 1.09 KB
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
34
35
36
37
38
class Solution {
public:
int sumOfGoodSubsequences(vector<int>& nums) {
int n = nums.size();
long long mod = 1e9 + 7;
vector<long long> left(n, 0);
vector<long long> right(n, 0);
unordered_map<int, long long> leftNumCnt;
unordered_map<int, long long> rightNumCnt;
for (int i = 0; i < n; ++i) {
int num = nums[i];
left[i] = leftNumCnt[num - 1] + leftNumCnt[num + 1];
left[i] %= mod;
leftNumCnt[num] += left[i] + 1;
leftNumCnt[num] %= mod;
}
for (int i = n - 1; i >= 0; --i) {
int num = nums[i];
right[i] = rightNumCnt[num - 1] + rightNumCnt[num + 1];
right[i] %= mod;
rightNumCnt[num] += right[i] + 1;
rightNumCnt[num] %= mod;
}
long long res = 0;
for (int i = 0; i < n; ++i) {
long long cnt = left[i] + right[i] + left[i] * right[i] + 1;
cnt %= mod;
res += cnt * nums[i];
res %= mod;
}
return res;
}
};