-
Notifications
You must be signed in to change notification settings - Fork 0
/
DP-longestIncreasingSeq-o(nlogn).cpp
67 lines (50 loc) · 1.22 KB
/
DP-longestIncreasingSeq-o(nlogn).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
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
//Function to find length of longest increasing subsequence.
int longestSubsequence(int n, int a[])
{
int dp[n+1];
for(int i=1;i<=n;i++){
dp[i]=INT_MAX;
}
dp[0]=INT_MIN;
for(int i=0;i<n;i++){
int idx=upper_bound(dp,dp+n+1,a[i])-dp;
if(a[i]>dp[idx-1] and a[i]<dp[idx]){
dp[idx]=a[i];
}
}
int ma=0;
for(int i=n;i>=0;i--){
if(dp[i]!=INT_MAX){
ma=i;
break;
}
}
return ma;
}
};
// { Driver Code Starts.
int main()
{
//taking total testcases
int t,n;
cin>>t;
while(t--)
{
//taking size of array
cin>>n;
int a[n];
//inserting elements to the array
for(int i=0;i<n;i++)
cin>>a[i];
Solution ob;
//calling method longestSubsequence()
cout << ob.longestSubsequence(n, a) << endl;
}
}
// } Driver Code Ends