Simplest C++ sol using Map in O(N) and neat clean code

interview-questions
Tags: #<Tag:0x00007f182cb68938>

#1

int Solution::longestConsecutive(const vector &A) {

map<int, int> mp;

for(auto &i: A)
{
    mp[i]=1; //put all elements in map 
}

int ans=INT_MIN;

for(auto &i:mp)
{
    int a = i.first;
    if(mp[a-1])  // check whether small by 1 is present in map 
    {
        mp[a]=mp[a-1]+1;
    }
}
for(auto &i:mp)
{
    ans = max(ans, i.second);  // find maximum ans 
}

return ans;

}