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 modulo109 + 7.
Note that a subsequence of size 1 is considered good by definition.
Example 1:
Input:nums = [1,2,1]
Output:14
Explanation:
Good subsequences are: [1], [2], [1], [1,2], [2,1], [1,2,1].
The sum of elements in these subsequences is 14.
Example 2:
Input:nums = [3,4,5]
Output:40
Explanation:
Good subsequences are: [3], [4], [5], [3,4], [4,5], [3,4,5].
The sum of elements in these subsequences is 40.
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 105
Solutions
Solution 1
Thinking
A good subsequence has consecutive absolute differences equal to \(1\). With \(n \le 10^5\) we cannot list subsequences; we DP on values.
Let \(g[x]\) be the number of good subsequences ending with \(x\) and \(f[x]\) their element sum. A new \(x\) starts a singleton or appends to existing \(x-1\) or \(x+1\).
Appending adds “old sum + old count \(\times x\)”. Updates follow input order so earlier copies of \(x\) are included. The answer is the sum of all \(f\), modulo \(10^9+7\).