Sum the sums of all subarrays that form a good arithmetic sequence.
An arithmetic sequence is a list of numbers where subtracting any number from the previous one always gives a constant difference. A good arithmetic sequence is an arithmetic sequence with a common difference of either 1 or -1. For example, [4, 5, 6] is good, and any sequence with only one element, such as [4], is good.
Given an integer array nums, return the sum of the sums of each subarray that is a good arithmetic sequence.
Example: nums = [7, 4, 5, 6, 5]. The good subarrays are [7], [4], [5], [6], [5], [4, 5], [5, 6], [6, 5] and [4, 5, 6]. Their sums are 7, 4, 5, 6, 5, 9, 11, 11 and 15, so the answer is 73.
Hint from the candidate: find the start and end of each sequence and count how many segments each number appears in.
Format · Google L3 onsite.
Community answers
Related questions
Sum all arithmetic-progression subarrays with common difference 0 or 1.Find the sum of max minus min over all subarrays.Find the maximum length of a good subarray.Related courses


