Skip to content

Commit 5fca426

Browse files
committed
Longest Consecutive Sequence
1 parent 99fa4b3 commit 5fca426

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#include<iostream>
2+
#include<unordered_map>
3+
#include<vector>
4+
using namespace std;
5+
int longestconsecutiveSeq(vector<int>& nums){
6+
unordered_map<int, bool> mp;
7+
for(int i = 0; i < nums.size(); i++){
8+
mp[nums[i]] = true;
9+
}
10+
for(int i = 0; i < nums.size(); i++){
11+
if(mp.find(nums[i] - 1) != mp.end()){
12+
mp[nums[i]] = false;
13+
}
14+
}
15+
int maxLen = 0;
16+
for(int i = 0; i < nums.size(); i++){
17+
if(mp[nums[i]]){
18+
int j = 0;
19+
int count = 0;
20+
while(mp.count(nums[i] + j) > 0){
21+
j++;
22+
count++;
23+
}
24+
if(count > maxLen){
25+
maxLen = count;
26+
}
27+
}
28+
}
29+
return maxLen;
30+
}
31+
int main(){
32+
int n;
33+
cout << "Enter the number of elements in the array: ";
34+
cin >> n;
35+
vector<int> nums(n);
36+
cout << "Enter the elements of the array: ";
37+
for(int i = 0; i < n; i++){
38+
cin >> nums[i];
39+
}
40+
int result = longestconsecutiveSeq(nums);
41+
cout << "Length of the longest consecutive sequence: " << result << endl;
42+
return 0;
43+
}

0 commit comments

Comments
 (0)