[LeetCode] Longest Subsequence With Decreasing Adjacent Difference

3409. Longest Subsequence With Decreasing Adjacent Difference

You are given an array of integers nums.

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|.

Return the length of such a subsequence.

A subsequence is an non-empty array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
int fenwick[301][303];
void update(int n, int k, int x) {
while(k < 303) {
fenwick[n][k] = max(fenwick[n][k], x);
k += k & -k;
}
}
int query(int n, int k) {
int res = 0;
while(k) {
res = max(res, fenwick[n][k]);
k -= k & -k;
}
return res;
}
class Solution {
public:
int longestSubsequence(vector<int>& nums) {
memset(fenwick, 0, sizeof fenwick);
int n = nums.size(), res = 0;
unordered_set<int> us{nums[0]};
for(int i = 1; i < n; i++) {
if(us.count(nums[i])) {
int now = query(nums[i], 301) + 1;
res = max(res, now);
update(nums[i], 301, now);
}
for(auto& u : us) {
if(u == nums[i]) continue;
int now = query(u, 300 - abs(u - nums[i]) + 1) + 1;
res = max(res, now);
update(nums[i], 300 - abs(u - nums[i]) + 1, now);
}

us.insert(nums[i]);
}
return res + 1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/01/05/PS/LeetCode/longest-subsequence-with-decreasing-adjacent-difference/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.