Beats 100%(T.C.) | Clean and Concise Code | DP tabulation
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time 
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n![image.png](https://assets.leetcode.com/users/images/635aebdb-03af-4431-8ffa-30de760794dd_1708279637.861258.png)\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` C++ []\nclass Solution {\npublic:\n    int maxSelectedElements(vector<int>& nums) {\n        unordered_map<int,int>dp;\n        int ans=0;\n        sort(nums.begin(),nums.end());\n        for(int &i:nums){\n            dp[i+1]=dp[i]+1;\n            dp[i]=dp[i-1]+1;\n            ans=max({ans,dp[i+1],dp[i]});\n        }   \n        return ans;\n    }\n};\n```\n\n\n```java []\npublic class Solution {\n    public int maxSelectedElements(int[] nums) {\n        Map<Integer, Integer> dp = new HashMap<>();\n        int ans = 0;\n        Arrays.sort(nums);\n        for (int i : nums) {\n            dp.put(i + 1, dp.getOrDefault(i, 0) + 1);\n            dp.put(i, dp.getOrDefault(i - 1, 0) + 1);\n            ans = Math.max(ans, Math.max(dp.get(i + 1), dp.get(i)));\n        }\n        return ans;\n    }\n}\n```\n\n\n\n
['C++', 'Java']