[Geeks for Geeks] Longest Increasing Subsequence

Longest Increasing Subsequence

Given an array of integers, find the length of the longest (strictly) increasing subsequence from the given array.

  • Time : O(nlogn)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution
{
public:
//Function to find length of longest increasing subsequence.
int longestSubsequence(int n, int a[])
{
vector<int> lcs;
for(int i = 0; i < n; i++) {
if(lcs.empty() or lcs.back() < a[i]) lcs.push_back(a[i]);
else {
auto it = lower_bound(begin(lcs), end(lcs), a[i]);
*it = a[i];
}
}

return lcs.size();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/20/PS/GeeksforGeeks/longest-increasing-subsequence/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.