Simple || Sorting + 1D DP
Please upvote if you like the code !!!\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n\n# Code\n\nclass Solution {\npublic:\n    in
**Please upvote if you like the code !!!**\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n    int maxSelectedElements(vector<int>& arr) {\n        int n=arr.size();\n        int mv=arr[0];\n        for (int i: arr) mv = max(mv, i);\n\n        int dp[mv+2];\n        memset(dp, 0, sizeof(dp));\n\n        int ans=1;\n        sort(arr.begin(), arr.end());\n\n        for (int i=0; i<n; i++){\n          ans = max(ans, dp[arr[i]-1] +1);\n          ans = max(ans, dp[arr[i]] + 1);\n\n          int v1 = dp[arr[i]-1];\n          int v2 = dp[arr[i]];\n          dp[arr[i]+1] = v2+1;\n          dp[arr[i]] = v1+1;\n        }\n        return ans;\n    }\n};\n```
['C++']