27(May) Longest subsequence-1
27. Longest Subsequence-1
The problem can be found at the following link: Question Link
Problem Description
Given an integer array a[] of size n, find the length of the longest subsequence such that the absolute difference between adjacent elements is 1.
Example:
Input:
n = 7
a[] = {10, 9, 4, 5, 4, 8, 6}Output:
3Explanation: The three possible subsequences of length 3 are {10, 9, 8}, {4, 5, 4}, and {4, 5, 6}, where adjacent elements have an absolute difference of 1. No valid subsequence of greater length could be formed.
My Approach
Initialization:
Create a dictionary
dpto store the length of the longest subsequence ending at each element.Initialize a variable
ansto keep track of the maximum subsequence length found.
Dynamic Programming Calculation:
Iterate through the array
a.For each element
xina:Calculate the lengths of the subsequences ending at
x - 1andx + 1.Update
dp[x]to the maximum length between its current value and the new lengths found.Update
answith the maximum value ofdp[x].
Return:
Return the value of
ans, which contains the length of the longest subsequence where the absolute difference of adjacent elements is 1.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n^2), as we iterate through the array once and perform constant-time operations for each element.
Expected Auxiliary Space Complexity: O(n), as we use a dictionary to store the lengths of the subsequences for each unique element in the array.
Code
C++
Java
Python
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated