Very Intuitive just Do space optimization with dp :))
Complexity

Time complexity:
O(nlogn+n)=> O(nlogn)


Space complexity:
O(max_element+2)

Code
# Complexity
- Time complexity:
    O(n*logn+n)=> O(n*logn)

- Space complexity:
    O(max_element+2)

# Code
```cpp []
class Solution 
{
public:
    int maxSelectedElements(vector<int>& nums) 
    {
        int n = nums.size();
        int m = 0;
        for(auto num:nums)        
        {
            m = max(m,num);
        }
        sort(nums.begin(),nums.end());
        vector<int> dp(m+2,0);
        int ans = 0;
        for(int i=1;i<=n;i++)
        {
            dp[nums[i-1]+1]= max({dp[nums[i-1]+1],1+dp[nums[i-1]]});
            dp[nums[i-1]]= max({dp[nums[i-1]],1+dp[nums[i-1]-1]});
            ans = max({ans,dp[nums[i-1]],dp[nums[i-1]+1]});
        }
        return ans;   
    }
};
```
['Dynamic Programming', 'C++']