#446

Arithmetic Slices II - Subsequence

expert · 1295 · lc hard +32 · verified · 54.9% accepted · 3,502 likes · top 48%

play →

Description

Given an integer array nums, count all distinct arithmetic subsequences with at least 3 elements. A subsequence is arithmetic when adjacent pairs all share the same difference (e.g., [1,3,5,7,9], [7,7,7,7]). Subsequences preserve relative index order and duplicates are not double-counted.

The answer fits in a 32-bit integer.

Example 1:

Input: nums = [2,4,6,8,10]
Output: 7
Explanation: All arithmetic subsequence slices are:
[2,4,6]
[4,6,8]
[6,8,10]
[2,4,6,8]
[4,6,8,10]
[2,4,6,8,10]
[2,6,10]

Example 2:

Input: nums = [7,7,7,7,7]
Output: 16
Explanation: Any subsequence of this array is arithmetic.

Code

1
2
3