[Geeks for Geeks] Longest consecutive subsequence

Longest consecutive subsequence

Given an array of positive integers. Find the length of the longest sub-sequence such that elements in the subsequence are consecutive integers, the consecutive numbers can be in any order.

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
// arr[] : the input array
// N : size of the array arr[]

//Function to return length of longest subsequence of consecutive integers.
int findLongestConseqSubseq(int arr[], int N) {
vector<int> dp(100003, 0);
int res = 0;
for(int i = 0; i < N; i++) {
int n = arr[i] + 1;
if(dp[n] != 0) continue;
int left = n - dp[n - 1], right = n + dp[n + 1];
dp[n] = dp[left] = dp[right] = dp[n - 1] + dp[n + 1] + 1;
res = max(res, dp[n]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/20/PS/GeeksforGeeks/longest-consecutive-subsequence/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.