I spent the first few minutes trying to enumerate subarrays and immediately knew that was going nowhere fast.
Use a sliding window to identify maximal contiguous segments where adjacent elements differ by exactly ±1. For each segment of length L, compute the sum of all subarray sums using the contribution of each element based on its position within the segment, then sum these contributions across all segments. This yields an O(N) solution by processing each element once.
Pro tip: Clarify that singleton subarrays are included and that the condition applies to every adjacent pair within the subarray. Emphasize that the O(N) complexity is achieved by avoiding nested loops and using arithmetic to compute contributions in constant time per element.
Scan the array and split it into maximal contiguous segments where each adjacent pair differs by exactly +1 or -1. Use a single pass, starting a new segment when the condition fails.
For a segment of length L, the sum of all subarray sums can be computed as the sum over each element of its value multiplied by the number of subarrays containing it. The number of subarrays containing the element at index i (0-based) is (i+1)*(L-i).
Instead of iterating over each element in the segment to compute the weighted sum, derive a formula or use a running sum to compute the total in O(1) per segment. For example, precompute prefix sums or use the fact that the weights form a pattern.
Sum the contributions from all segments to get the final answer. Ensure that singleton segments (length 1) are handled correctly, contributing their value once.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.