Sum of Consecutive Subsequences Problem
Description
LeetCode Problem 3299.
We call an array arr of length n consecutive if one of the following holds:
arr[i] - arr[i - 1] == 1for all1 <= i < n.arr[i] - arr[i - 1] == -1for all1 <= i < n.
The value of an array is the sum of its elements.
For example, [3, 4, 5] is a consecutive array of value 12 and [9, 8] is another of value 17. While [3, 4, 3] and [8, 6] are not consecutive.
Given an array of integers nums, return the sum of the values of all consecutive non-empty subsequences.
Since the answer may be very large, return it modulo 10^9+ 7.
Note that an array of length 1 is also considered consecutive.
Example 1:
Input: nums = [1,2]
Output: 6
Explanation:
The consecutive subsequences are: [1], [2], [1, 2].
Example 2:
Input: nums = [1,4,2,3]
Output: 31
Explanation:
The consecutive subsequences are: [1], [4], [2], [3], [1, 2], [2, 3], [4, 3], [1, 2, 3].
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^5
Solution
Approach: Counting Each Element's Contribution
Every subsequence of length 1 contributes just its element, so the sum of all elements is part of the answer. For longer subsequences, count how many increasing consecutive subsequences (steps of +1) each element belongs to, and multiply by the element. Decreasing ones are handled by reversing the array.
For an element nums[i], let left be the number of increasing runs on its left that end with value nums[i] - 1, and right the number of increasing runs on its right that start with value nums[i] + 1. The element is in left + right + left * right runs of length at least 2. Both counts come from one pass each, using a table indexed by value: the number of runs ending at v is 1 + (runs ending at v - 1) added to its previous count.
Compute this for the array, reverse the array and compute it again, then add the sum of all elements. Reduce counts modulo 10^9 + 7 as you go.
Complexity: O(n) time and O(n) space, where n is the length of nums.
class Solution:
def getSum(self, nums: List[int]) -> int:
def calc(nums: List[int]) -> int:
n = len(nums)
left = [0] * n
right = [0] * n
cnt = Counter()
for i in range(1, n):
cnt[nums[i - 1]] = (cnt[nums[i - 1]] + 1 + cnt[nums[i - 1] - 1]) % mod
left[i] = cnt[nums[i] - 1]
cnt = Counter()
for i in range(n - 2, -1, -1):
cnt[nums[i + 1]] = (cnt[nums[i + 1]] + 1 + cnt[nums[i + 1] + 1]) % mod
right[i] = cnt[nums[i] + 1]
return sum((l + r + l * r) * x for l, r, x in zip(left, right, nums)) % mod
mod = 10**9 + 7
x = calc(nums)
nums.reverse()
y = calc(nums)
return (x + y + sum(nums)) % mod