Description Link to heading
446. Arithmetic Slices II - Subsequence (Hard)
Given an integer array nums
, return the number of all the arithmetic subsequences of nums
.
A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
- For example,
[1, 3, 5, 7, 9]
,[7, 7, 7, 7]
, and[3, -1, -5, -9]
are arithmetic sequences. - For example,
[1, 1, 2, 5, 7]
is not an arithmetic sequence.
A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.
- For example,
[2,5,10]
is a subsequence of[1,2,1,2,4,1,5,10]
.
The test cases are generated so that the answer fits in 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.
Constraints:
1 <= nums.length <= 1000
-2³¹ <= nums[i] <= 2³¹ - 1
Solution Link to heading
This problem evidently calls for a dynamic programming approach. For instance, let $dp[i]$ denote the length of the subsequence ending with nums[i]
. To transition from $dp[j]$, we must be aware of $nums[i] - nums[j]$. Consequently, the $dp$ array requires two dimensions: the first dimension represents the index of the array $nums$, and the second dimension denotes the difference $diff$. As $diff$ can be substantial and even negative, we employ a hash table for record-keeping.
Hence, vector<unordered_map<long, long>> dp
.
Furthermore, there’s the requirement that the array length must be at least $3$. Eliminating sequences of length $2$ during the state transition process can be somewhat intricate. However, we can easily remove length-$2$ sequences after computation by subtracting $\binom{n}{2}$ from the result.
Code Link to heading
class Solution {
public:
int numberOfArithmeticSlices(vector<int> &nums) {
if (nums.size() < 3) {
return 0;
}
int n = nums.size();
int res = 0;
vector<unordered_map<long, long>> dp(n);
for (int i = 1; i < n; ++i) {
for (int j = 0; j < i; ++j) {
long diff = (long)nums[i] - nums[j];
dp[i][diff] += 1 + dp[j][diff];
res += 1 + dp[j][diff];
}
}
return res - n * (n - 1) / 2;
}
};