You are given an integer array nums. A good subsequence is defined as a subsequence of nums where the absolute difference between any two consecutive elements in the subsequence is exactly 1.
Return the sum of all possiblegood subsequences of nums.
Since the answer may be very large, return it modulo10^9 + 7.
Note that a subsequence of size 1 is considered good by definition.
Input: nums =[1,2,1]Output: 14Explanation:
* Good subsequences are:`[1]`,`[2]`,`[1]`,`[1,2]`,`[2,1]`,`[1,2,1]`.* The sum of elements in these subsequences is14.
Input: nums =[3,4,5]Output: 40Explanation:
* Good subsequences are:`[3]`,`[4]`,`[5]`,`[3,4]`,`[4,5]`,`[3,4,5]`.* The sum of elements in these subsequences is40.
Let cnt[x] be the count of x in nums. For each value x, let dp[x] be the sum of all good subsequences ending with x. For each x in nums, dp[x] = cnt[x] * (dp[x-1] + dp[x+1] + 1), since you can append x to any good subsequence ending with x-1 or x+1, or start a new subsequence with x. The answer is the sum of dp[x] * x for all x.
#include<vector>#include<unordered_map>usingnamespace std;
classSolution {
public:int sumOfGoodSubsequences(vector<int>& nums) {
constint MOD =1e9+7, N =1e5+2;
vector<longlong> cnt(N), dp(N);
for (int x : nums) cnt[x]++;
longlong ans =0;
for (int x =0; x < N; ++x) {
if (cnt[x] ==0) continue;
dp[x] = (cnt[x] * ((x >0? dp[x-1] :0) + (x+1< N ? dp[x+1] :0) +1)) % MOD;
ans = (ans + dp[x] * x) % MOD;
}
return (int)ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
publicintsumOfGoodSubsequences(int[] nums) {
int MOD = 1_000_000_007, N = 100_002;
long[] cnt =newlong[N], dp =newlong[N];
for (int x : nums) cnt[x]++;
long ans = 0;
for (int x = 0; x < N; ++x) {
if (cnt[x]== 0) continue;
dp[x]= cnt[x]* ((x > 0 ? dp[x-1] : 0) + (x+1 < N ? dp[x+1] : 0) + 1) % MOD;
ans = (ans + dp[x]* x) % MOD;
}
return (int)ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funsumOfGoodSubsequences(nums: IntArray): Int {
val MOD = 1_000_000_007L
val N = 100_002
val cnt = LongArray(N)
val dp = LongArray(N)
for (x in nums) cnt[x]++var ans = 0Lfor (x in0 until N) {
if (cnt[x] ==0L) continue dp[x] = cnt[x] * ((if (x > 0) dp[x-1] else0L) + (if (x+1 < N) dp[x+1] else0L) + 1L) % MOD
ans = (ans + dp[x] * x) % MOD
}
return ans.toInt()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
defsumOfGoodSubsequences(self, nums: list[int]) -> int:
MOD =10**9+7 N =10**5+2 cnt = [0]*(N)
dp = [0]*(N)
for x in nums:
cnt[x] +=1 ans =0for x in range(N):
if cnt[x] ==0:
continue dp[x] = cnt[x] * ((dp[x-1] if x >0else0) + (dp[x+1] if x+1< N else0) +1) % MOD
ans = (ans + dp[x] * x) % MOD
return ans