Sum of Good Subsequences - Problem
You're given an integer array nums and need to find all "good subsequences" - but what makes a subsequence good?
A good subsequence is one where each pair of consecutive elements has an absolute difference of exactly 1. Think of it like a staircase where each step is exactly one unit up or down!
Your task: Calculate the sum of all elements in all possible good subsequences. Since this number can be astronomically large, return the result modulo 109 + 7.
Key insights:
- A single element is always a good subsequence
- Elements don't need to be adjacent in the original array
- Focus on consecutive differences in the subsequence, not original positions
Example: For [1, 2, 1], good subsequences include [1], [2], [1], [1,2], [2,1], and [1,2,1].
Input & Output
example_1.py โ Basic Case
$
Input:
[1, 2, 1]
โบ
Output:
14
๐ก Note:
Good subsequences: [1] (sum=1), [2] (sum=2), [1] (sum=1), [1,2] (sum=3), [2,1] (sum=3), [1,2,1] (sum=4). Total: 1+2+1+3+3+4 = 14
example_2.py โ Single Element
$
Input:
[3]
โบ
Output:
3
๐ก Note:
Only one good subsequence possible: [3] with sum = 3
example_3.py โ No Adjacent Differences
$
Input:
[1, 3, 5]
โบ
Output:
9
๐ก Note:
No consecutive elements differ by 1, so only single-element subsequences are good: [1], [3], [5]. Total: 1+3+5 = 9
Constraints
- 1 โค nums.length โค 105
- 1 โค nums[i] โค 105
- A subsequence of size 1 is always considered good
- Return the result modulo 109 + 7
Visualization
Tap to expand
Understanding the Visualization
1
Track Melody Endings
For each note value, remember how many melodies end there and their total value
2
Extend Compatible Melodies
When we see a new note, extend melodies ending one semitone away (ยฑ1)
3
Update State
Add the new note as both a solo melody and extension of existing ones
4
Accumulate Value
Sum all melody values created so far
Key Takeaway
๐ฏ Key Insight: Instead of generating all melodies explicitly, we track how many melodies end at each note and their total value, then efficiently extend compatible melodies as we encounter new notes!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code