My first instinct was to enumerate subarrays and it took me an embarrassingly long time to accept that wasn't going to hit O(N).
Use a linear scan to identify maximal good subarrays by checking adjacent differences. For each maximal good subarray of length L, compute the sum of all its subarray sums using a contribution technique, then sum these across all maximal good subarrays.
Pro tip: Emphasize that the O(N) solution relies on decomposing the array into maximal good subarrays and using a formula for the sum of all subarray sums within each, avoiding nested loops. This demonstrates both algorithmic insight and optimization skill.
Scan the array once and split it into maximal contiguous segments where each adjacent pair differs by exactly 1. Each segment is a maximal good subarray.
For a segment of length L with elements a[0..L-1], the sum of all subarray sums is Σ_{i=0}^{L-1} a[i] * (i+1) * (L-i). This can be computed in O(L) time.
For each maximal good subarray, compute its total contribution using the formula and add it to the overall answer.
Consider arrays of length 0 or 1, and ensure the algorithm works when no good subarray of length >1 exists.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.