Arithmetic Slices II

Hard Topics Company Tags

Count the subsequences of nums that have at least three elements and the same difference between every consecutive pair of chosen values. The chosen indices must stay in their original order, but do not need to be adjacent.

Different choices of indices count separately, even if they produce identical values. The difference may be positive, negative, or zero. The inputs are chosen so that the answer fits in a signed 32-bit integer.

Example 1:

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

Output: 3

Explanation: The valid subsequences are [1,3,5], [3,5,7], and [1,3,5,7]. Each has constant difference 2, so the answer is 3.

Example 2:

Input: nums = [4,4,4,4]

Output: 5

Explanation: There are four ways to choose three indices and one way to choose all four. Every resulting sequence has difference zero, giving 5 subsequences.

Example 3:

Input: nums = [3,1,-1]

Output: 1

Explanation: The full array is the only subsequence with at least three elements. Its consecutive differences are both -2, so it contributes one.

Constraints:

  • 1 <= nums.length <= 1000
  • -2147483648 <= nums[i] <= 2147483647
  • The answer is at most 2147483647.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.