#3409
Longest Subsequence With Decreasing Adjacent Difference
MediumArrayDynamic ProgrammingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
We can use dynamic programming to track the longest subsequence while considering the differences between elements.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a DP array where dp[i] stores the longest subsequence ending at index i.
- 2Step 2: For each pair of indices (i, j), calculate the absolute difference and update dp[i] based on valid previous indices.
- 3Step 3: Return the maximum value in the DP array.
solution.py13 lines
1def longestDecreasingSubsequence(nums):
2 n = len(nums)
3 dp = [1] * n
4 max_len = 1
5 for i in range(n):
6 for j in range(i):
7 diff1 = abs(nums[i] - nums[j])
8 if dp[j] > 1:
9 diff2 = abs(nums[j] - nums[j-1])
10 if diff1 >= diff2:
11 dp[i] = max(dp[i], dp[j] + 1)
12 max_len = max(max_len, dp[i])
13 return max_lenℹ
Complexity note: The nested loop checks pairs, leading to O(n²), while the DP array requires O(n) space.
- 1The absolute differences must be non-increasing.
- 2Dynamic programming is effective for subsequence problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.