java
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\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n    public int maxSelectedElements(int[] nums) {\n        Arrays.sort(nums);\n        int[] dp = new int[1000002];\n        for (int num : nums) {\n            dp[num + 1] = 1 + dp[num];\n            dp[num] = Math.max(dp[num], 1 + dp[num - 1]);\n        }\n        int max = 0;\n        for (int i : dp) {\n            max = Math.max(max, i);\n        }\n        return max;\n    }\n}\n```
['Java']