Given an array arr[0 … n-1] containing n positive integers, a subsequence of arr[] is called Bitonic if it is first increasing, then decreasing. Write a function that takes an array as argument and returns the length of the longest bitonic subsequence. A sequence, sorted in increasing order is considered Bitonic with the decreasing part as empty. Similarly, decreasing order sequence is considered Bitonic with the increasing part as empty. Examples:
Input arr[] = {1, 11, 2, 10, 4, 5, 2, 1};
Output: 6 (A Longest Bitonic Subsequence of length 6 is 1, 2, 10, 4, 2, 1)
Input arr[] = {12, 11, 40, 5, 3, 1}
Output: 5 (A Longest Bitonic Subsequence of length 5 is 12, 11, 5, 3, 1)
Input arr[] = {80, 60, 30, 40, 20, 10}
Output: 5 (A Longest Bitonic Subsequence of length 5 is 80, 60, 30, 20, 10)
Longest Bitonic Subsequence | DP-15 - GeeksforGeeks
class Solution{
public:
int LongestBitonicSequence(vector<int>nums)
{
int n = nums.size();
vector<int> lis(n),lisr(n);
for(int i=0;i<n;i++)
{
lis[i] = 1;
lisr[i] = 1;
}
for(int i=1;i<n;i++)
{
for(int j=0;j<i;j++)
{
if(nums[i]>nums[j] and lis[i]<1+lis[j])
lis[i] = 1+lis[j];
}
}
for(int i=n-2;i>=0;i--)
{
for(int j=n-1;j>i;j--)
{
if(nums[i]>nums[j] and lisr[i]<1+lisr[j])
lisr[i] = 1+lisr[j];
}
}
int res = 0;
for(int i=0;i<n;i++)
{
res = max(res,lis[i]+lisr[i]-1);
}
return res;
}
};
// Time Complexity : O(n^2)