0% completed
Problem Statement
Given a number sequence, find the length of its Longest Bitonic Subsequence (LBS). A subsequence is considered bitonic if it is monotonically increasing and then monotonically decreasing.
Example 1:
Input: {4,2,3,6,10,1,12}
Output: 5
Explanation: The LBS is {2,3,6,10,1}.
Example 2:
Input: {4,2,5,9,7,6,10,3,1}
Output: 7
Explanation: The LBS is {4,5,9,7,6,3,1}.
Basic Solution
A basic brute-force solution could be to try finding the Longest Decreasing Subsequences (LDS), starting from every number in both directions. So for every index 'i' in the given array, we will do two things:
- Find LDS starting from 'i' to the end of the array.
- Find LDS starting from 'i' to the beginning of the array.
LBS would be the maximum sum of the above two subsequences.
Code
Here is the code:
The time complexity of the above algorithm is exponential O(2^n), where 'n' is the lengths of the input array. The space complexity is O(n) which is used to store the recursion stack.
Top-down Dynamic Programming with Memoization
To overcome the overlapping subproblems, we can use an array to store the already solved subproblems.
We need to memoize the recursive functions that calculate the longest decreasing subsequence. The two changing values for our recursive function are the current and the previous index. Therefore, we can store the results of all subproblems in a two-dimensional array. (Another alternative could be to use a hash-table whose key would be a string (currentIndex + "|" + previousIndex)).
Code
Here is the code:
Bottom-up Dynamic Programming
The above algorithm shows us a clear bottom-up approach. We can separately calculate LDS for every index i.e., from the beginning to the end of the array and vice versa. The required length of LBS would be the one that has the maximum sum of LDS for a given index (from both ends).
Code
Here is the code for our bottom-up dynamic programming approach:
The time complexity of the above algorithm is O(n^2) and the space complexity is O(n).
.....
.....
.....
Table of Contents
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible