Python | DP | O(nlogn)
Code\n\nfrom collections import defaultdict\nclass Solution:\n    def maxSelectedElements(self, nums: List[int]) -> int:\n        d = defaultdict(int)\n        
# Code\n```\nfrom collections import defaultdict\nclass Solution:\n    def maxSelectedElements(self, nums: List[int]) -> int:\n        d = defaultdict(int)\n        nums.sort()\n        for num in nums:\n            d[num+1] = d[num] + 1\n            d[num] = d[num-1]+1\n        return max(d.values())\n        \n        \n```
['Python3']