Longest Subsequence With Decreasing Adjacent Difference Problem
Description
LeetCode Problem 3409.
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 seq_0, seq_1, seq_2, ..., seq_m of nums, |seq_1 - seq_0| >= |seq_2 - seq_1| >= ... >= |seq_m - seq_(m - 1)|.
Return the length of such a subsequence.
Example 1:
Input: nums = [16,6,3]
Output: 3
Explanation:
The longest subsequence is [16, 6, 3] with the absolute adjacent differences [10, 3].
Example 2:
Input: nums = [6,5,3,4,2,1]
Output: 4
Explanation:
The longest subsequence is [6, 4, 2, 1] with the absolute adjacent differences [2, 2, 1].
Example 3:
Input: nums = [10,20,10,19,10,20]
Output: 5
Explanation:
The longest subsequence is [10, 20, 10, 19, 10] with the absolute adjacent differences [10, 10, 9, 9].
Constraints:
2 <= nums.length <= 10^41 <= nums[i] <= 300
Solution
Approach: Dynamic Programming over Value and Last Difference
Values are at most 300, so every difference is below 300. Let g[v][d] be the length of the longest valid subsequence that ends with value v and whose last difference is at least d.
Process the numbers in order. For a new number x and every earlier value y we have seen, the new difference is d = |x - y|. Appending x to a subsequence ending at y is allowed when its last difference is at least d, which gives length g[y][d] + 1; two numbers alone also give length 2. Collect these lengths per difference in a temporary array, take a suffix maximum from large to small differences (a subsequence whose last difference is d also counts for every smaller d), and merge the result into g[x]. The answer is the largest length seen.
Complexity: O(n * V) time and O(V^2) space, where V is the largest value (300).
class Solution:
def longestSubsequence(self, nums: List[int]) -> int:
m = max(nums)
# g[v][d]: longest valid subsequence ending with value v whose last difference is >= d
g = [[0] * (m + 2) for _ in range(m + 1)]
seen = [False] * (m + 1)
ans = 1
for x in nums:
cur = [0] * (m + 2)
for y in range(m + 1):
if seen[y]:
d = abs(x - y)
cur[d] = max(cur[d], g[y][d] + 1, 2)
for d in range(m, -1, -1):
cur[d] = max(cur[d], cur[d + 1])
if cur[d] > g[x][d]:
g[x][d] = cur[d]
seen[x] = True
ans = max(ans, cur[0])
return ans