Video Explanation (Optimising top-down solution step by step)
Explanation\n\nClick here for the video\n\n# Code\n\nclass Solution {\npublic:\n    int maxSelectedElements(vector<int>& nums) {\n        sort (nums.begin(), nu
# Explanation\n\n[Click here for the video](https://youtu.be/pGwkuwMUuPM)\n\n# Code\n```\nclass Solution {\npublic:\n    int maxSelectedElements(vector<int>& nums) {\n        sort (nums.begin(), nums.end());\n        \n        int n = nums.size();\n        vector<int> dp(1e6+2, 0);\n        \n        for (int j = n-1; j >= 0; j --) {\n            dp[nums[j]] = max(dp[nums[j]], 1+dp[nums[j]+1]);\n            dp[nums[j]+1] = max(dp[nums[j]+1], 1+dp[nums[j]+2]);\n        }\n        \n        int ans = 0;\n        for (auto i : dp) ans = max(ans, i);\n        return ans;\n    }\n};\n```
['C++']