O(1) Space DP
Code\npython3\nclass Solution:\n    def maxSelectedElements(self, nums: List[int]) -> int:\n        nums.sort()\n        n = len(nums)\n        ans, f, g = 1, 1
# Code\n```python3\nclass Solution:\n    def maxSelectedElements(self, nums: List[int]) -> int:\n        nums.sort()\n        n = len(nums)\n        ans, f, g = 1, 1, 1\n        for i in range(1, n):\n            match nums[i] - nums[i - 1]:\n                case 2:\n                    f, g = g + 1, 1\n                    if f > ans: ans = f\n                case 1:\n                    f, g = max(f + 1, g), g + 1\n                    ans = max(ans, f, g)\n                case 0:\n                    g = max(f + 1, g)\n                    if g > ans: ans = g\n                case _:\n                    f, g = 1, 1\n        return ans\n```
['Dynamic Programming', 'Sorting', 'Python3']