-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
longest_bitonic_subsequence.cpp
73 lines (64 loc) · 1.24 KB
/
longest_bitonic_subsequence.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
using namespace std;
//Longest Increasing Decreasing Subsequence
int lidss(int n,int arr[])
{
if(n==0)
return 0;
int lenI[n];
int lenD[n];
for(int i=0; i<n; i++)
{
lenI[i]=1;
lenD[i]=1;
}
//calculating increasing subsequence
for(int i=1; i<n; i++)
{
for(int j=0; j<i; j++)
{
if(arr[j]<arr[i] && lenI[i]<lenI[j]+1)
{
lenI[i]=lenI[j]+1;
}
}
}
//calculating decreasing subsequence
for(int i=n-2; i>=0; i--)
{
for(int j=n-1; j>i; j--)
{
if(arr[j]<arr[i] && lenD[i]<lenD[j]+1)
{
lenD[i]=lenD[j]+1;
}
}
}
//calculate longest Increasing and then decreasing subsequence starting from each element
int max=1;
for(int i=0; i<n; i++)
{
int len=lenI[i]+lenD[i]-1;
if(max<len)
{
max=len;
}
}
return max;
}
int main() {
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int arr[n];
for(int i=0; i<n; i++)
{
cin>>arr[i];
}
cout<<lidss(n,arr)<<endl;
}
return 0;
}