![]() |
VOOZH | about |
Given an array of N integers, find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in strictly decreasing order.
Examples:
Input: arr[] = [15, 27, 14, 38, 63, 55, 46, 65, 85]
Output: 3
Explanation: The longest decreasing subsequence is {63, 55, 46}
Input: arr[] = {50, 3, 10, 7, 40, 80}
Output: 3
Explanation: The longest decreasing subsequence is {50, 10, 7}
The problem can be solved using Dynamic Programming
Optimal Substructure:
Let arr[0...n-1] be the input array and lds[i] be the length of the LDS ending at index i such that arr[i] is the last element of the LDS.
Then, lds[i] can be recursively written as:
lds[i] = 1 + max(lds[j]) where i > j > 0 and arr[j] > arr[i] or
lds[i] = 1, if no such j exists.
To find the LDS for a given array, we need to return max(lds[i]) where n > i > 0.
Length of LDS is 3
Time Complexity: O(n2)
Auxiliary Space: O(n)
Related Article: https://www.geeksforgeeks.org/dsa/longest-increasing-subsequence-dp-3/
Longest Decreasing Subsequence in O(n*log(n)) :
Another approach to finding the Longest Decreasing Subsequence is using the Longest Increasing Subsequence approach in n*log(n) complexity. Here is the link to find the details of the approach with O(n*log(n)) complexity https://www.geeksforgeeks.org/dsa/longest-monotonically-increasing-subsequence-size-n-log-n/
We can observe that the length of the Longest Decreasing Subsequence of any array is same as the length of the Longest Increasing Subsequence of that array if we multiply all elements by -1.
For example:
arr[] = [15, 27, 14, 38, 63, 55, 46, 65, 85]
then the length of longest decreasing subsequence of this array is same as length of longest increasing subsequence of arr[]=[-15, -27, -14, -38, -63, -55, -46, -65, -85]In both cases the length is 3.
Steps to solve this problem:
1. Check if array is zero than return zero.
2. Declare a vector tail of array size.
3. Declare a variable length=1.
4. Initialize tail[0]=v[0].
5. Iterate through i=1 till size of array:
*Initialize auto b=tail.begin and e=tail.begin+length.
*Initialize auto it to lower bound of v[i].
*Check if it is equal to tail.begin+length than tail[length++]=v[i].
*Else update value at it =v[i].
6. Return length.
Below is the code of the above approach.
Length of Longest Decreasing Subsequence is 3
Time Complexity: O(n*logn)
Auxiliary Space: O(n)