[C++/Python]✅Beats 100% | Easy Solution | 8 Lines | Dynamic Progromming
Approach : Dynamic Programming\n Describe your approach to solving the problem. \n\n# Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. 
# Approach : Dynamic Programming\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n![image.png](https://assets.leetcode.com/users/images/020d5b9f-261c-4cfd-afcc-3a51872756ba_1708265635.2703247.png)\n\n\n# Code : <span style="color:green">Accepted</span>\n``` C++ []\nclass Solution {\npublic:\n    int maxSelectedElements(vector<int>& nums) {\n        unordered_map<int,int>dp;\n        sort(nums.begin(), nums.end());\n        int ans = 0;\n        for(int &x:nums){\n            dp[x+1] = dp[x] + 1;\n            dp[x] = dp[x-1] + 1;\n            ans = max({ans, dp[x], dp[x+1]});\n        }\n        return ans;\n    }\n};\n```\n``` Python []\nclass Solution(object):\n    def maxSelectedElements(self, nums):\n        dp = {}\n        nums.sort()\n        ans = 0\n        for x in nums:\n            dp[x+1] = dp.get(x, 0) + 1\n            dp[x] = dp.get(x-1, 0) + 1\n            ans = max(ans, dp[x], dp[x+1])\n        return ans\n```
['Dynamic Programming', 'Python', 'C++']