File tree Expand file tree Collapse file tree 1 file changed +48
-48
lines changed Expand file tree Collapse file tree 1 file changed +48
-48
lines changed Original file line number Diff line number Diff line change 2
2
using namespace std ;
3
3
4
4
// Longest Increasing Decreasing Subsequence
5
- int lidss (int n,int arr[])
5
+ int lidss (int n,int arr[])
6
6
{
7
- if (n==0 )
7
+ if (n==0 )
8
8
return 0 ;
9
- int lenI[n];
10
- int lenD[n];
11
-
12
- for (int i=0 ;i<n;i++)
13
- {
14
- lenI[i]=1 ;
15
- lenD[i]=1 ;
16
- }
17
-
18
- // calculating increasing subsequence
19
- for (int i=1 ;i<n;i++)
9
+ int lenI[n];
10
+ int lenD[n];
11
+
12
+ for (int i=0 ; i<n; i++)
13
+ {
14
+ lenI[i]=1 ;
15
+ lenD[i]=1 ;
16
+ }
17
+
18
+ // calculating increasing subsequence
19
+ for (int i=1 ; i<n; i++)
20
+ {
21
+ for (int j=0 ; j<i; j++)
20
22
{
21
- for ( int j= 0 ;j<i;j++ )
23
+ if (arr[j]<arr[i] && lenI[i]<lenI[j]+ 1 )
22
24
{
23
- if (arr[j]<arr[i] && lenI[i]<lenI[j]+1 )
24
- {
25
- lenI[i]=lenI[j]+1 ;
26
- }
25
+ lenI[i]=lenI[j]+1 ;
27
26
}
28
27
}
29
-
30
- // calculating decreasing subsequence
31
- for (int i=n-2 ;i>=0 ;i--)
28
+ }
29
+
30
+ // calculating decreasing subsequence
31
+ for (int i=n-2 ; i>=0 ; i--)
32
+ {
33
+ for (int j=n-1 ; j>i; j--)
32
34
{
33
- for ( int j=n- 1 ;j>i;j-- )
35
+ if (arr[j]<arr[i] && lenD[i]<lenD[j]+ 1 )
34
36
{
35
- if (arr[j]<arr[i] && lenD[i]<lenD[j]+1 )
36
- {
37
- lenD[i]=lenD[j]+1 ;
38
- }
37
+ lenD[i]=lenD[j]+1 ;
39
38
}
40
39
}
41
-
42
- // calculate longest Increasing and then decreasing subsequence starting from each element
43
- int max=1 ;
44
- for (int i=0 ;i<n;i++)
45
- {
40
+ }
41
+
42
+ // calculate longest Increasing and then decreasing subsequence starting from each element
43
+ int max=1 ;
44
+ for (int i=0 ; i<n; i++)
45
+ {
46
46
int len=lenI[i]+lenD[i]-1 ;
47
47
if (max<len)
48
48
{
49
- max=len;
49
+ max=len;
50
50
}
51
- }
52
- return max;
51
+ }
52
+ return max;
53
53
}
54
54
55
55
int main () {
56
- int t;
57
- cin>>t;
58
- while (t--)
59
- {
60
- int n;
61
- cin>>n;
62
- int arr[n];
63
- for (int i=0 ;i<n;i++)
64
- {
65
- cin>>arr[i];
66
- }
67
- cout<<lidss (n,arr)<<endl;
68
- }
69
- return 0 ;
56
+ int t;
57
+ cin>>t;
58
+ while (t--)
59
+ {
60
+ int n;
61
+ cin>>n;
62
+ int arr[n];
63
+ for (int i=0 ; i<n; i++)
64
+ {
65
+ cin>>arr[i];
66
+ }
67
+ cout<<lidss (n,arr)<<endl;
68
+ }
69
+ return 0 ;
70
70
}
71
71
72
72
You can’t perform that action at this time.
0 commit comments