LeetCode - 1218. Longest Arithmetic Subsequence of Given Difference
Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic
sequence such that the difference between adjacent elements in the subsequence equals difference.
Input: arr = [1,2,3,4], difference = 1 Output: 4
Explanation: The longest arithmetic subsequence is [1,2,3,4].
Input: arr = [1,3,5,7], difference = 1 Output: 1
Explanation: The longest arithmetic subsequence is any single element.
Input: arr = [1,5,7,8,5,3,4,2,1], difference = -2 Output: 4
Explanation: The longest arithmetic subsequence is [7,5,3,1].
用一个map存储每个值为结尾的最长等差数列的长度即可,因为是map所以也不需要考虑负数的问题,而且因为初始化都是自动是0,所以特不需要考虑初始化的问题。
int longestSubsequence(vector<int>& arr, int d) {
unordered_map<int,int> mp;
int res = 1;
for(const int &i : arr) {
mp[i] = 1 + mp[i - d];
res = max(res, mp[i]);
}
return res;
}
还有一道题,是给一个已排序数组,问最长等差序列子数组多长,这道题和 LIS 基本一模一样。可以先算出最大差是多少,作为dp矩阵第二维的大小。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> v(n);
for (int& i : v) cin >> i;
const int max_diff = v.back() - v[0];
int max_len = 1;
vector<vector<int>> dp(n, vector<int>(max_diff + 1, 1));
for (int i = 1; i < n; ++i)
for (int j = i - 1; j >= 0; --j) {
const int d = v[i] - v[j];
dp[i][d] = max(dp[i][d], dp[j][d] + 1);
max_len = max(max_len, dp[i][d]);
}
cout << max_len << endl;
}