-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongest-contgous-subsequence.cpp
More file actions
44 lines (39 loc) · 1.06 KB
/
longest-contgous-subsequence.cpp
File metadata and controls
44 lines (39 loc) · 1.06 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<bits/stdc++.h>
using namespace std;
// Returns length of the longest contiguous subsequence
int findLongestConseqSubseq(int arr[], int n)
{
unordered_set<int> S;
int ans = 0;
// Hash all the array elements
for (int i = 0; i < n; i++)
S.insert(arr[i]);
// check each possible sequence from the start
// then update optimal length
for (int i=0; i<n; i++)
{
// if current element is the starting
// element of a sequence
if (S.find(arr[i]-1) == S.end())
{
// Then check for next elements in the
// sequence
int j = arr[i];
while (S.find(j) != S.end())
j++;
// update optimal length if this length
// is more
ans = max(ans, j - arr[i]);
}
}
return ans;
}
// Driver program
int main()
{
int arr[] = {1, 9, 3, 10, 4, 20, 2};
int n = sizeof arr/ sizeof arr[0];
cout << "Length of the Longest contiguous subsequence is "
<< findLongestConseqSubseq(arr, n);
return 0;
}