Your task is to find the length of the longest subsequence seq of
nums, such that the absolute differences between consecutive elements form a non-increasing sequence of integers. In other words, for a subsequence seq0, seq1, seq2, …, seqm of nums, |seq1 - seq0| >= |seq2 - seq1| >= ... >= |seqm - seqm - 1|.
We want the longest subsequence where the absolute differences between consecutive elements form a non-increasing sequence. For each pair, we can try to extend a previous valid subsequence if the new difference is not greater than the last one.
classSolution {
publicintlongestSubsequence(int[] nums) {
int n = nums.length, ans = 1;
Map<Integer, Integer>[] dp =new HashMap[n];
for (int i = 0; i < n; i++) dp[i]=new HashMap<>();
for (int i = 0; i < n; i++) {
dp[i].put(0, 1);
for (int j = 0; j < i; j++) {
int d = Math.abs(nums[i]- nums[j]);
for (int prevD : dp[j].keySet()) {
if (prevD >= d) {
int l = dp[j].get(prevD) + 1;
dp[i].put(d, Math.max(dp[i].getOrDefault(d, 0), l));
ans = Math.max(ans, dp[i].get(d));
}
}
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution {
funlongestSubsequence(nums: IntArray): Int {
val n = nums.size
var ans = 1val dp = Array(n) { mutableMapOf(0 to 1) }
for (i in0 until n) {
for (j in0 until i) {
val d = kotlin.math.abs(nums[i] - nums[j])
for ((prevD, l) in dp[j]) {
if (prevD >= d) {
dp[i][d] = maxOf(dp[i].getOrDefault(d, 0), l + 1)
ans = maxOf(ans, dp[i][d]!!)
}
}
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
deflongestSubsequence(self, nums: list[int]) -> int:
n = len(nums)
dp = [{} for _ in range(n)]
ans =1for i in range(n):
dp[i][0] =1for j in range(i):
d = abs(nums[i] - nums[j])
for prev_d, l in dp[j].items():
if prev_d >= d:
dp[i][d] = max(dp[i].get(d, 0), l +1)
ans = max(ans, dp[i][d])
return ans
impl Solution {
pubfnlongest_subsequence(nums: Vec<i32>) -> i32 {
let n = nums.len();
letmut dp =vec![std::collections::HashMap::new(); n];
letmut ans =1;
for i in0..n {
dp[i].insert(0, 1);
for j in0..i {
let d = (nums[i] - nums[j]).abs();
for (&prev_d, &l) in&dp[j] {
if prev_d >= d {
let entry = dp[i].entry(d).or_insert(0);
*entry = (*entry).max(l +1);
ans = ans.max(*entry);
}
}
}
}
ans
}
}