C++, DP, 100% faster
```\n\n\nclass Solution {\npublic:\n    int maxSelectedElements(vector& nums) {\n        \n        int n = nums.size();\n        \n        sort(nums.begin(), nu
```\n\n\nclass Solution {\npublic:\n    int maxSelectedElements(vector<int>& nums) {\n        \n        int n = nums.size();\n        \n        sort(nums.begin(), nums.end());\n\n        int dp[n][2]; // max ans in range [i.....j] if previous element is decreased or not decreased\n        \n        \n        // dp[i][x]= max ans for [0.....i], x denotes either increasing nums[i] (x=1) or not increasing nums[i] (x=0)\n\n        dp[0][0]=1;\n        \n        dp[0][1]=1;\n    \n        \n        for (int i = 1; i < n; ++i) {\n            \n            if (nums[i] - nums[i - 1] == 2) {   // e.g nums[i-1]=4, num[i]=6, increase nums[i-1] by 1\n                \n                dp[i][0] = dp[i - 1][1] + 1;  // nums[i-1] increased by 1\n                \n                \n                dp[i][1]=1;   // incraese nums[i] by 1, then searies start from nums[i] so dp[i][1]=1\n                \n            } else if(nums[i]-nums[i-1]==0){  // e.g nums[i-1] =4, nums[i]=4, incraese nums[i] to continue the series by 1, if not increasing nums[i] then keep continuing the series\n               \n                dp[i][1]= dp[i-1][0]+1;\n                \n                dp[i][0]=dp[i-1][0]; \n                \n                \n            }\n            else if(nums[i]-nums[i-1]==1){  // e.g nums[i-1]=4, nums[i]=5, either incraese both or not incraese both\n                \n    \n                 dp[i][0]=dp[i-1][0]+1;\n                \n                dp[i][1]=dp[i-1][1]+1;\n                \n                \n            }\n            \n            else{\n                \n                dp[i][0]=1;\n                \n                dp[i][1]=1;\n            }\n            \n            \n        }\n\n        // Find the maximum value in the dp array\n        int maxConsecutive = 0;\n        for (int i = 0; i < n; ++i) {\n            maxConsecutive = max(maxConsecutive, max(dp[i][0], dp[i][1]));\n        }\n\n        return maxConsecutive;\n    }\n};\n
['Dynamic Programming']