hashmap + dp make it easy
Intuition\n Describe your first thoughts on how to solve this problem. \nObviously, sorting will be helpful since it mentions in the problem that we will sort\n
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nObviously, sorting will be helpful since it mentions in the problem that we will sort\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(nlogn) since we need to sort\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n) since we use hashmap\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    int maxSelectedElements(vector<int>& nums) {\n        sort(nums.begin(), nums.end());\n        unordered_map<int,int> dp;\n        unordered_map<int,int> freq;\n\n        int res = 0;\n        for (int num : nums) {\n            \n            //first handle nums\n            if (freq[num-1] == 0 && freq[num] == 0) {\n                dp[num] = dp[num-1] + 1;\n                dp[num+1] = 1;\n            }\n            else if (freq[num] == 0) {\n                dp[num+1] = dp[num] + 1;\n                dp[num] = dp[num-1] + 1;\n            }\n            else {\n                dp[num+1] = dp[num] + 1;\n            }\n            res = max(max(res, dp[num]), dp[num+1]);\n            freq[num]++;\n\n        }      \n\n        return res;\n    }   \n};\n```
['C++']