Skip to content

Commit 944ae42

Browse files
authored
Adding longest increasing subsequence in O(nlogn)
1 parent 9c8ee8d commit 944ae42

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

LIS_in_O(nlogn).cpp

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
//Note that the below code works only for distinct longest increasing subsequence
5+
// If you want also want duplicate elements in LIS then change lower_bound to upper_bound and it will account for duplicates as well
6+
7+
int main() {
8+
int n;
9+
cin >> n;
10+
vector<int> dp;
11+
12+
for (int i = 0; i < n; i++) {
13+
int x;
14+
cin >> x;
15+
auto it = lower_bound(dp.begin(), dp.end(), x);
16+
if (it == dp.end()) {
17+
dp.push_back(x);
18+
} else {
19+
*it = x;
20+
}
21+
}
22+
23+
cout << dp.size() << endl;
24+
}

0 commit comments

Comments
 (0)