144. Sum of All Good Arithmetic Sequences

Asked in

Sum of All Good Arithmetic Sequences
An arithmetic sequence is a list of numbers where the difference between every pair of adjacent elements is the same constant.

A good arithmetic sequence is an arithmetic sequence whose common difference is either 1 or -1.

For example, [4, 5, 6] is a good arithmetic sequence, and any sequence that has only one element is also a good arithmetic sequence.

You are given a list of integers nums. Return the sum of the sums of all contiguous subarrays that are good arithmetic sequences.

A subarray is a contiguous non-empty part of the list.

Method Signature

long sumOfGoodArithmeticSubarrays(List<Integer> nums)
  • nums is the input list of integers.
  • A subarray of length 1 is always a good arithmetic sequence.
  • For a subarray of length at least 2, either every adjacent difference is 1 or every adjacent difference is -1.
  • Return the total sum obtained by adding the sum of every good arithmetic subarray.

Rules

A subarray is considered valid if it satisfies one of the following:
  • subarray.size() = 1
  • For every i from 1 to subarray.size() - 1, subarray[i] - subarray[i - 1] = 1
  • For every i from 1 to subarray.size() - 1, subarray[i] - subarray[i - 1] = -1

Constraints

  • 1 ≤ nums.size() ≤ 200,000
  • -1,000,000,000 ≤ nums[i] ≤ 1,000,000,000
  • The returned answer will always fit in a signed 64-bit integer.

Examples

Example 1

sumOfGoodArithmeticSubarrays(nums = [7, 4, 5, 6, 5])

Output: 73

Explanation:

The good arithmetic subarrays are:
[7], [4], [5], [6], [5], [4, 5], [5, 6], [6, 5], [4, 5, 6]

Their sums are:
7, 4, 5, 6, 5, 9, 11, 11, 15

Total:
7 + 4 + 5 + 6 + 5 + 9 + 11 + 11 + 15 = 73

Example 2

sumOfGoodArithmeticSubarrays(nums = [1, 2, 3, 4])

Output: 50

Explanation:

Every contiguous subarray is a good arithmetic sequence because all adjacent differences are 1.

The sums are:
Length 1: 1 + 2 + 3 + 4 = 10
Length 2: (1 + 2) + (2 + 3) + (3 + 4) = 3 + 5 + 7 = 15
Length 3: (1 + 2 + 3) + (2 + 3 + 4) = 6 + 9 = 15
Length 4: 1 + 2 + 3 + 4 = 10

Total:
10 + 15 + 15 + 10 = 50

Example 3

sumOfGoodArithmeticSubarrays(nums = [5, 4, 3, 5])

Output: 45

Explanation:

The good arithmetic subarrays are:
[5], [4], [3], [5], [5, 4], [4, 3], [5, 4, 3]

Their sums are:
5, 4, 3, 5, 9, 7, 12

Total:
5 + 4 + 3 + 5 + 9 + 7 + 12 = 45




Please use Laptop/Desktop or any other large screen to add/edit code.