dynamic programming in python3
We record two state variables, the number t we are now picking as the end one, and whether we are picking it as it is, or we want to increase it by one.\n\nIn t
We record two state variables, the number t we are now picking as the end one, and whether we are picking it as it is, or we want to increase it by one.\n\nIn the first case, we look for t-1 or t-2 in the nums (thus we need a dict to make the searching a rapid one)\n\nIn the second case, we look for t-1 or t it self in the nums. But note we have used one t in nums, so there should be at least two ts if we want to use one increased, one as it is.\n\nThere is no need to sort as we don\'t care about indices at all.\n\nThe last number could be any one in the number set, select the one yielding the largest partial result.\n\n\n# Code\n```\nclass Solution:\n    def maxSelectedElements(self, nums: List[int]) -> int:\n        n = len(nums)\n        freq = Counter(nums)\n        @cache\n        def dp(t,increased):\n            if increased:\n                res = 1\n                if t-1 in freq:\n                    res = max(res,1+dp(t-1,True))\n                if freq[t] >1:\n                    res = max(res,1+dp(t,False))\n            else:\n                res = 1\n                if t-1 in freq:\n                    res = max(res,1+dp(t-1,False))\n                if t-2 in freq:\n                    res = max(res,1+dp(t-2,True))\n            return res\n        res = 1\n        for a in freq:\n            res = max(res,dp(a,True),dp(a,False))\n        return res\n            \n        \n```
['Dynamic Programming', 'Python3']