LeetCode 3409: Longest Subsequence With Decreasing Adjacent Difference Solution
Master LeetCode problem 3409 (Longest Subsequence With Decreasing Adjacent Difference), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3409. Longest Subsequence With Decreasing Adjacent Difference
Problem Explanation
Explanation:
To solve this problem, we can use dynamic programming. We will create a dp array where dp[i] represents the length of the longest subsequence ending at index i. For each index i, we iterate over all previous indices j (0 <= j < i) and update dp[i] to be the maximum of dp[i] and dp[j] + 1 if the absolute difference between nums[i] and nums[j] is less than or equal to the absolute difference between nums[j] and the last element in the subsequence ending at index j.
Finally, we return the maximum value in the dp array as the length of the longest subsequence with decreasing adjacent difference.
- Time complexity: O(n^2) where n is the number of elements in the input array nums.
- Space complexity: O(n) for the dp array.
:
Solution Code
class Solution {
public int longestSubsequence(int[] nums) {
int n = nums.length;
int[] dp = new int[n];
Arrays.fill(dp, 1);
int maxLen = 1;
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (Math.abs(nums[i] - nums[j]) <= Math.abs(nums[j] - nums[i - 1])) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
maxLen = Math.max(maxLen, dp[i]);
}
return maxLen;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3409 (Longest Subsequence With Decreasing Adjacent Difference)?
This page provides optimized solutions for LeetCode problem 3409 (Longest Subsequence With Decreasing Adjacent Difference) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3409 (Longest Subsequence With Decreasing Adjacent Difference)?
The time complexity for LeetCode 3409 (Longest Subsequence With Decreasing Adjacent Difference) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3409 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3409 in Java, C++, or Python.