913. Sum of Consecutive Subsequences
We define an array arr of length n to be consecutive if one of the following conditions holds for every index i with 1 ≤ i < n:
- arr[i] - arr[i - 1] == 1, or
- arr[i] - arr[i - 1] == -1.
The value of an array is the sum of its elements. For example, [3, 4, 5] is consecutive (since each difference is 1) with a value of 3 + 4 + 5 = 12, and [9, 8] is consecutive (each difference is -1) with a value of 9 + 8 = 17. In contrast, arrays like [3, 4, 3] or [8, 6] are not consecutive.
Given an integer array nums, your task is to calculate the sum of the values of all consecutive non-empty subsequences of nums.
Here, a subsequence is formed by deleting zero or more elements from nums without changing the order of the remaining elements (note that any single element is considered consecutive by definition).
Since the answer can be very large, return it modulo 10⁹ + 7.
Example 1:
Input : nums = [2, 3]
Output : 10
Explanation :
The valid consecutive subsequences are:
- [2] with sum = 2
- [3] with sum = 3
- [2, 3] with sum = 2 + 3 = 5
Total sum = 2 + 3 + 5 = 10
Example 2:
Input : nums = [7, 8, 9]
Output : 80
Explanation :
The valid consecutive subsequences are:
- Single-element: [7], [8], [9] with sums 7, 8, and 9 respectively.
- Two-element: [7, 8] (sum = 7 + 8 = 15) and [8, 9] (sum = 8 + 9 = 17).
- Three-element: [7, 8, 9] (sum = 7 + 8 + 9 = 24).
Total sum = 7 + 8 + 9 + 15 + 17 + 24 = 80
Now Your Turn!
Pick the correct output for the given inputInput : nums = [10, 9, 8, 1]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 ≤ nums.length ≤ 10⁵
- 1 ≤ nums[i] ≤ 10⁵