Longest Increasing Subsequence
- Time : O(nlogn)
- Space : O(n)
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
| #include <vector> using namespace std;
vector<int> longestIncreasingSubsequence(vector<int> array) { int n = array.size(); vector<int> lis; vector<int> record(n); for(int i = 0; i < n; i++) { if(lis.empty() or lis.back() < array[i]) { lis.push_back(array[i]); record[i] = lis.size() - 1; } else { auto j = lower_bound(begin(lis), end(lis), array[i]) - begin(lis); lis[j] = array[i]; record[i] = j; } } vector<int> res; for(int i = n - 1, r = lis.size() - 1; i >= 0; i--) { if(record[i] == r) { res.push_back(array[i]); r--; } } reverse(begin(res), end(res)); return res; }
|