Skip to content

3351. Sum of Good Subsequences

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.

A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.

Return the sum of all possible good subsequences of nums.

Since the answer may be very large, return it modulo 109 + 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

Solution:

class Solution {
    public int sumOfGoodSubsequences(int[] nums) {
        final int MOD = 1_000_000_007;
        int mx = 0;
        for (int x : nums) {
            mx = Math.max(mx, x);
        }

        int[] f = new int[mx + 3];
        int[] cnt = new int[mx + 3];
        for (int x : nums) {
            // 为避免出现 -1,所有下标加一
            long c = cnt[x] + cnt[x + 2] + 1;
            f[x + 1] = (int) ((x * c + f[x] + f[x + 1] + f[x + 2]) % MOD);
            cnt[x + 1] = (int) ((cnt[x + 1] + c) % MOD);
        }

        long ans = 0;
        for (int s : f) {
            ans += s;
        }
        return (int) (ans % MOD);
    }
}