Python DP after sort
Just sort first.  Let DP[x] be the maximum length of a sequence that ends at x, with 0 being value if none exist.\nWhen you encounter each number n, you can eit
Just sort first.  Let `DP[x]` be the maximum length of a sequence that ends at `x`, with 0 being value if none exist.\nWhen you encounter each number `n`, you can either (1) increment it so `dp[n+1] = dp[n]+1` with the caveat that `dp[n]=0` if none exists yet or (2) leave it as it is so `dp[n]=dp[n-1]+1`.\nAfter the loop simply return the max of values of `dp`.\n\nComplexity O(n log n) because of the sort.\nSpace O(n)\n\n```\nclass Solution:\n    def maxSelectedElements(self, nums: List[int]) -> int:\n        nums = sorted(nums)\n        dp = {}\n        \n        for n in nums:\n            dp[n+1] = dp.get(n,0)+1\n            dp[n] = dp.get(n-1,0)+1\n        \n        return max(dp.values())\n```\nFor extra credit, note that this solution uses O(n) space but doesn\'t need more than (at most) the last two values.  So you could be a little smarter and only save two 2-tuples at most. \n```\nclass Solution:\n    def maxSelectedElements(self, nums: List[int]) -> int:\n        nums = sorted(nums)\n        ret=0\n        dp={}\n\n        for n in nums:\n            dp[n+1] = dp.get(n,0)+1\n            dp[n] = dp.get(n-1,0)+1\n            ret=max(ret,max(dp.values()))\n            dp={k:v for k,v in dp.items() if k+1>=n}\n\n        return ret\n\t```
[]