In this problem, a "good subsequence" is defined as a subsequence where the absolute difference between any two consecutive elements is exactly 1. You are given an array of integers and need to find the sum of the elements of all possible "good subsequences." Since the result can be very large, return it modulo . Note that identical subsequences starting at different indices are counted separately.
Google asks this Hard-level problem to test a candidate's proficiency in Dynamic Programming and combinatorics. It's not enough to count the subsequences; you must also track the sum of their elements. This requires maintaining two DP states simultaneously (count and sum), making it a great test of logical structuring.
The pattern is "Dynamic Programming with Frequency Hashing." We use two maps or arrays:
count[x]: Number of good subsequences ending with value x.total_sum[x]: The sum of all elements of all good subsequences ending with value x.
As we iterate through the array and see a value v, it can extend any good subsequence ending in v-1 or v+1.count[v] = count[v] + count[v-1] + count[v+1] + 1 (the +1 is for the subsequence starting and ending at v).total_sum[v] is updated by adding the sums of existing subsequences and the contribution of the new element v.Array: [1, 2, 1]
count[1] = 1, total_sum[1] = 1.count[2] = count[1] + 1 = 2. total_sum[2] = (total_sum[1] + 2*count[1]) + 2 = (1 + 2) + 2 = 5. (Subsequences: [2], [1, 2])count[1] = count[1] + count[2] + 1 = 1 + 2 + 1 = 4. total_sum[1] is updated similarly.
The total result is the sum of total_sum[x] for all x.C adds the new value v exactly C times to the total sum.When a problem asks for the "sum of elements" across many combinations, try to track both the "number of ways" and the "running sum" in your DP. This is a very common pattern in counting problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find the Maximum Length of a Good Subsequence II | Hard | Solve | |
| Longest Arithmetic Subsequence of Given Difference | Medium | Solve | |
| Length of Longest Fibonacci Subsequence | Medium | Solve | |
| Delete and Earn | Medium | Solve | |
| Find the Maximum Length of a Good Subsequence I | Medium | Solve |