Problem Description
Given an array of integers nums, a subarray is called consecutive if the differences between adjacent elements are either 1 (increasing) or -1 (decreasing). Even a single element is considered consecutive. The value of a subarray is defined as the sum of its elements. The task is to compute the sum of the values of all consecutive subarrays within nums. Since the result can be very large, return it modulo 10^9+7.
Key Insights
- Every individual element constitutes a valid consecutive subarray.
- A dynamic programming (DP) or one-pass approach can be used to aggregate contributions from subarrays ending at each index.
- If nums[i] continues a consecutive pattern (difference of exactly 1 or -1 from nums[i-1]), then all consecutive subarrays ending at i−1 can be extended to i.
- Use a count to represent how many consecutive subarrays end at the previous element and update the cumulative sum accordingly.
- The recurrence: If consecutive, then:
count[i] = count[i-1] + 1
dp[i] = nums[i] + dp[i-1] + (count[i-1]) * nums[i]
Otherwise, reset count[i] = 1 and dp[i] = nums[i]. - The overall answer is the sum of dp[i] for all indices i.
Space and Time Complexity
Time Complexity: O(n) – we iterate through the list once.
Space Complexity: O(1) – only a few auxiliary variables are used.
Solution
We traverse the array while maintaining two variables: one for the cumulative sum of consecutive subarray sums ending at the previous index (prevSum) and another to keep the count of such subarrays (count). At each index, if the current element continues the consecutive pattern with the previous element (either increasing by 1 or decreasing by 1), we increment count and update prevSum by adding:
nums[i] (starting a new subarray), plus
prevSum (extending all previous consecutive subarrays) plus
(nums[i] multiplied by the previous count) (additional contribution when extending each subarray).
If the pattern breaks, reset count to 1 and prevSum to nums[i]. The final answer is the modulo sum of all prevSum values computed over the traversal.