• Source
    1. #include<bits/stdc++.h>
    2. #define ll long long int
    3. using namespace std;
    4.  
    5. int longestConsecutive(const vector<int> &A) {
    6. unordered_map<int,int> mp;
    7. int l1,l2;
    8. for(int i=0;i<A.size();i++) {
    9. if(mp.find(A[i]-1)!=mp.end() || mp.find(A[i]+1)!=mp.end()) {
    10. l1=mp[A[i]-1];
    11. if(mp.find(A[i]+1)!=mp.end())
    12. l2=mp[A[i]+1];
    13. int l=l1+l2+1;
    14. int LB=A[i]-l1;
    15. int RB=A[i]+l2;
    16. mp[LB]=l;
    17. if(mp.find(A[i]+1)!=mp.end())
    18. mp[RB]=l;
    19. mp.insert({A[i],l});
    20. }
    21. else mp[A[i]]=1;
    22. }
    23. int res=mp[A[0]];
    24. for(int i=1;i<A.size();i++) {
    25. res=max(res,mp[A[i]]);
    26. }
    27. return res;
    28. }
    29.  
    30.  
    31. int main() {
    32. int n;
    33. cin>>n;
    34. vector<int> a(n);
    35. for(int i=0;i<n;i++)
    36. cin>>a[i];
    37. cout<<"\n"<<longestConsecutive(a);
    38. }
    39.