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
classSolution { public: // arr[] : the input array // N : size of the array arr[]
//Function to return length of longest subsequence of consecutive integers. intfindLongestConseqSubseq(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; } };