Python - Dynamic programming with caching
Code\n\nclass Solution:\n    def maxSelectedElements(self, nums: List[int]) -> int:\n        self.nums1 = sorted(nums)\n        self.nums2 = [k + 1 for k in sel
# Code\n```\nclass Solution:\n    def maxSelectedElements(self, nums: List[int]) -> int:\n        self.nums1 = sorted(nums)\n        self.nums2 = [k + 1 for k in self.nums1]\n        res = 1\n        \n        for idx, val in enumerate(self.nums1):\n            res = max(res, self.runner(idx + 1, val) + 1)\n        for idx, val in enumerate(self.nums2):\n            res = max(res, self.runner(idx + 1, val) + 1)\n            \n        return res\n    \n    @cache\n    def runner(self, position, last):\n        if position > len(self.nums1) - 1:\n            return 0\n        res = 0\n        \n        if self.nums1[position] == last + 1:\n            res = max(res, self.runner(position + 1, last + 1)) + 1\n\n        if self.nums2[position] == last + 1:\n            res = max(res, self.runner(position + 1, last + 1)) + 1\n        \n        if self.nums2[position] == last:\n            res = max(res, self.runner(position + 1, last))\n\n            \n        return res\n```
['Python3']