My first instinct was just enumerate all valid subarrays and sum them up, which is obviously not O(n).
First, clarify the definition of a 'good' subarray and confirm that the sum is over all elements in all such subarrays. Then, propose an O(n) solution by identifying maximal contiguous segments where adjacent elements differ by exactly 1, and for each segment, compute the sum of all subarrays within it using a formula based on prefix sums and contributions.
Pro tip: Mention that the sum of all subarray sums can be computed by summing each element's contribution (value multiplied by the number of subarrays containing it), which simplifies the calculation and avoids explicit enumeration.
Ask if 'good' subarray means every adjacent pair differs by exactly 1 (absolute difference). Confirm that the total sum is the sum of all elements in all good subarrays.
Scan the array once to find maximal contiguous segments where each adjacent pair satisfies |a[i] - a[i+1]| == 1. These segments are the only places where good subarrays can exist.
For a segment of length L, the sum of all subarray sums can be computed in O(L) using prefix sums or by summing each element's contribution: element at index i (0-based) appears in (i+1)*(L-i) subarrays.
Sum the contributions from all maximal segments to get the total sum. Ensure the algorithm runs in O(n) by processing each element a constant number of times.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.