Good Subarray Sums

Asked at GoogleOnsite

Reported by the problem's creator, not verified

A subarray is a contiguous run of elements of an array. A subarray is good when it has exactly one element, or when every element is exactly 1 more than the one before it, or every element is exactly 1 less than the one before it. Subarrays at different positions count separately, even if they hold the same values.

Examples

  1. Example 1

    Input: nums = [3,5,6,7,6]

    Output: 82

    Explanation: The five single elements sum to 27. The good longer subarrays are [5, 6], [6, 7], [5, 6, 7] and [7, 6], summing to 11 + 13 + 18 + 13 = 55. Total 27 + 55 = 82.

  2. Example 2

    Input: nums = [1,2,3]

    Output: 20

    Explanation: The singles sum to 6, the pairs [1, 2] and [2, 3] to 3 + 5, and [1, 2, 3] to 6, giving 20.

Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question

Code

Loading editor…

Ln 1, Col 1

Start an attempt to use Coach.