Sum of Good Subsequences Problem
Description
LeetCode Problem 3351.
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 possible good subsequences of nums.
Since the answer may be very large, return it modulo 10^9 + 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 <= 10^50 <= nums[i] <= 10^5
Solution
Approach: Dynamic Programming over Values
A good subsequence has adjacent differences of exactly 1. Keep, for each value x, the number of good subsequences ending in x (g[x]) and the sum of their elements (f[x]).
Process the numbers in order. For a number x, the subsequences that end in it are the singleton [x], plus every subsequence ending in x-1 or x+1 extended with x. So the new count is 1 + g[x-1] + g[x+1] and the new sum is x * (that count) + f[x-1] + f[x+1]; add both to g[x] and f[x]. The answer is the sum of all f, modulo 10^9 + 7.
Complexity: O(n) time, O(M) space, where M is the maximum value.
from collections import defaultdict
class Solution:
def sumOfGoodSubsequences(self, nums: List[int]) -> int:
mod = 10**9 + 7
f = defaultdict(int)
g = defaultdict(int)
for x in nums:
f[x] += x
g[x] += 1
f[x] = (f[x] + f[x - 1] + g[x - 1] * x) % mod
g[x] = (g[x] + g[x - 1]) % mod
f[x] = (f[x] + f[x + 1] + g[x + 1] * x) % mod
g[x] = (g[x] + g[x + 1]) % mod
return sum(f.values()) % mod