A Bitonic Sequence is a sequence of numbers that is first strictly increasing and then strictly decreasing.
A strictly ascending order sequence is also considered bitonic, with the decreasing part as empty, and same for a strictly descending order sequence.
For example, the sequences [1, 3, 5, 3, 2], [1, 2, 3, 4] are bitonic, whereas the sequences [5, 4, 1, 4, 5] and [1, 2, 2, 3] are not.
You are given an array 'arr' consisting of 'n' positive integers.
Find the length of the longest bitonic subsequence of 'arr'.
Input: 'arr' = [1, 2, 1, 2, 1]
Output: 3
Explanation: The longest bitonic subsequence for this array will be [1, 2, 1]. Please note that [1, 2, 2, 1] is not a valid bitonic subsequence, because the consecutive 2's are neither strictly increasing, nor strictly decreasing.
The first line contains a single integer 'n' denoting the number of integers in the array.
The second line contains 'n' space-separated integers, denoting the elements of the array.
The output contains an integer, denoting the length of the longest bitonic subsequence.
You don’t need to print anything; it has already been taken care of. Just implement the given function.
5
1 2 1 2 1
3
The longest bitonic subsequence for this array will be [1, 2, 1]. Please note that [1, 2, 2, 1] is not a valid bitonic subsequence, because the consecutive 2's are neither strictly increasing, nor strictly decreasing.
5
1 2 1 3 4
4
The longest bitonic sequence for this array will be [1, 2, 3, 4].
The expected time complexity is O(n ^ 2).
1 <= 'n' <= 10^3
1 <= 'arr[i]' <= 10^5
Time Limit: 1sec
Can we solve this problem with the help of recursion?
The key observation here is that for each index ‘i’, of ‘arr’ the length of the bitonic sequence containing index ‘i’, will be the sum of the length of the longest increasing subsequence ending at ‘i’, and the length of longest decreasing subsequence beginning at ‘i’. We can use a recursive approach for finding the length of the longest increasing and decreasing subsequence.
The algorithm will be:
O(n * (2 ^ n)), where ‘n’ is the number of elements in ‘arr’.
As the total number of different states in the recursion tree for each recursive call while iterating, can be O(2 ^ n) the overall time complexity will be O(n * (2 ^ n)).
O(n), where ‘n’ is the number of elements in ‘arr’.
As there will be at most 2 * n different states of recursion that are stored in the recursion stack at a time. Hence, the space complexity will be O(n).