


There can be more than one subsequences with the longest length.
For the given array [5, 0, 3, 2, 9], the longest decreasing subsequence is of length 3, i.e. [5, 3, 2]
Try to solve the problem in O(N log N) time complexity.
The first line of input contains an integer 'T' representing the number of the test case. Then the test case follows.
The first line of each test case contains an integer ‘N’ representing the size of the array/list.
The second line of each test case contains N single space-separated integers representing the array/list elements.
For each test case, print the integer denoting the length of the longest decreasing subsequence.
Print the output of each test case in a separate line.
You do not need to print anything; it has already been taken care of. Just implement the given function.
1 <= T <= 50
1 <= N <= 5000
1 <= ARR[i] <= 10^9
Time Limit: 1 sec
We can use recursion to solve this problem.
In the recursive approach, many recursive calls had to be made again and again with the same set of parameters. This redundancy can be eliminated by storing the results obtained for a particular call in memory (as an array, MEMO) so that whenever we need to call the function again if we have stored its value earlier.
This can be done as:
The problem has optimal substructure. That means the problem can be broken down into smaller sub-problems, which can further be divided until the solution becomes trivial.
The solution also exhibits overlapping sub-problems. If we draw the recursion tree of the solution, we can see that the same sub-problems are getting computed again and again.
We know that problems having optimal substructure and overlapping subproblems can be solved by using Dynamic Programming.
We’ll solve this problem in a bottom-up manner. In this bottom-up approach, we will solve smaller subproblems first, then larger sub-problems from them.
The idea here is to maintain lists of decreasing sequences. In general, we have a set of active lists of varying length. We are adding an element A[i] to these lists. We can always add A[i] at a point just larger than it and we can show that this doesn't hamper the LDS. We scan the lists (for end elements) in decreasing order of their length. We will verify the end elements of all the lists to find a list whose end element is smaller than A[i] (floor value).
The basic conditions to create these lists will be:
We will discard all other lists of the same length as that of this modified list.
Note: At any instance during our construction of active lists, the following condition is maintained.
“The end element of a smaller list is smaller than the end elements of larger lists”.