#include <bits/stdc++.h>
using namespace std;
int longestSuccessiveElements(vector<int>&a) {
int n = a.size();
if (n == 0) return 0;
int longest = 1;
unordered_set<int> st;
//put all the array elements into set:
for (int i = 0; i < n; i++) {
st.insert(a[i]);
}
//Find the longest sequence:
for (auto it : st) {
//if 'it' is a starting number:
if (st.find(it - 1) == st.end()) {
//find consecutive numbers:
int cnt = 1;
int x = it;
while (st.find(x + 1) != st.end()) {
x = x + 1;
cnt = cnt + 1;
}
longest = max(longest, cnt);
}
}
return longest;
}
int main()
{
vector<int> a = {100, 200, 1, 2, 3, 4};
int ans = longestSuccessiveElements(a);
cout << "The longest consecutive sequence is " << ans << "\n";
return 0;
}
CgoKI2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgppbnQgbG9uZ2VzdFN1Y2Nlc3NpdmVFbGVtZW50cyh2ZWN0b3I8aW50PiZhKSB7CiAgICBpbnQgbiA9IGEuc2l6ZSgpOwogICAgaWYgKG4gPT0gMCkgcmV0dXJuIDA7CgogICAgaW50IGxvbmdlc3QgPSAxOwogICAgdW5vcmRlcmVkX3NldDxpbnQ+IHN0OwogICAgLy9wdXQgYWxsIHRoZSBhcnJheSBlbGVtZW50cyBpbnRvIHNldDoKICAgIGZvciAoaW50IGkgPSAwOyBpIDwgbjsgaSsrKSB7CiAgICAgICAgc3QuaW5zZXJ0KGFbaV0pOwogICAgfQoKICAgIC8vRmluZCB0aGUgbG9uZ2VzdCBzZXF1ZW5jZToKICAgIGZvciAoYXV0byBpdCA6IHN0KSB7CiAgICAgICAgLy9pZiAnaXQnIGlzIGEgc3RhcnRpbmcgbnVtYmVyOgogICAgICAgIGlmIChzdC5maW5kKGl0IC0gMSkgPT0gc3QuZW5kKCkpIHsKICAgICAgICAgICAgLy9maW5kIGNvbnNlY3V0aXZlIG51bWJlcnM6CiAgICAgICAgICAgIGludCBjbnQgPSAxOwogICAgICAgICAgICBpbnQgeCA9IGl0OwogICAgICAgICA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