Clean Code with Explanation
Intuition\n Describe your first thoughts on how to solve this problem. \nAs we have to give longest chain of consecutive elements after sorting , so their relat
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs we have to give longest chain of consecutive elements after sorting , so their relative order is not matter (as given in question)\n Now for every element there is two possibilities \n1. current number is increased by 1 \n2. currrent number is not increased by 1\n    \nSo for every element (let num) in array nums it can be num or num+1\nand we try to find whether their previous element is present or not.\nHence we try to find out whether num or num-1 is present or not \n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n<!-- - Space complexity: -->\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    int maxSelectedElements(vector<int>& nums) {\n        map<int,int>mp;\n        int f = 0;\n        sort(nums.begin(),nums.end());\n        for(auto it : nums){\n            int ans=1;\n            // if we increase the current num by 1\n            if(mp.find(it)!=mp.end()){\n              mp[it+1]=max(mp[it+1],1+mp[it]);\n            }\n            // if we not increase the current num by 1\n             if(mp.find(it-1)!=mp.end()){\n              mp[it]=max(mp[it],1+mp[it-1]);\n            }\n            // if we could not find previous consecutive element from current num or num+1\n            mp[it+1]=max(1,mp[it+1]);\n            mp[it]=max(mp[it],1);\n             // cout<<it<<" "<<mp[it]<<" "<<mp[it+1]<<endl;\n\n            f=max(mp[it+1],f);\n            f=max(f,mp[it]);\n\n            \n        }\n      return f;\n\n    }\n};\n```
['C++']