Sum of Consecutive Subsequences - Problem
Imagine you're analyzing stock price patterns where consecutive sequences represent trending periods. A sequence is consecutive if it's either:
- Increasing: Each element is exactly 1 more than the previous (
arr[i] - arr[i-1] == 1) - Decreasing: Each element is exactly 1 less than the previous (
arr[i] - arr[i-1] == -1)
For example: [3, 4, 5] is consecutive (increasing) with value 12, and [9, 8] is consecutive (decreasing) with value 17. However, [3, 4, 3] and [8, 6] are not consecutive.
Goal: Find the sum of values of all consecutive non-empty subsequences (not subarrays) in the given array. Since the result can be massive, return it modulo 109 + 7.
Note: A single element is always considered consecutive.
Input & Output
example_1.py โ Basic Consecutive Sequences
$
Input:
[1, 2, 4, 3]
โบ
Output:
20
๐ก Note:
Consecutive subsequences: [1]=1, [2]=2, [4]=4, [3]=3, [1,2]=3, [4,3]=7. Total: 1+2+4+3+3+7=20
example_2.py โ Single Element
$
Input:
[5]
โบ
Output:
5
๐ก Note:
Only one subsequence possible: [5] with value 5
example_3.py โ No Multi-Element Consecutives
$
Input:
[1, 3, 5, 7]
โบ
Output:
16
๐ก Note:
No consecutive subsequences of length > 1 possible. Only singles: [1]=1, [3]=3, [5]=5, [7]=7. Total: 1+3+5+7=16
Constraints
- 1 โค nums.length โค 105
- -109 โค nums[i] โค 109
- Answer fits in 32-bit integer after modulo operation
- Return result modulo 109 + 7
Visualization
Tap to expand
Understanding the Visualization
1
Identify Patterns
Scan through floor levels and identify which ones can form valid staircases
2
Track Endpoints
For each floor level, remember how many staircases end there and their total heights
3
Extend Sequences
When processing a new floor, extend existing staircases that can reach it (differ by ยฑ1)
4
Accumulate Results
Sum up all staircase heights to get the final inspection score
Key Takeaway
๐ฏ Key Insight: Use dynamic programming to track consecutive sequences by their endpoints. For each element, extend existing sequences that can reach it (differ by ยฑ1) and start new single-element sequences. This avoids generating all 2^n subsequences explicitly!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code