Faster than 100%, space efficient than 100%
Intuition\n Describe your first thoughts on how to solve this problem. \nBasically, after sorting the array four cases can arrive in this problem. One is when t
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBasically, after sorting the array four cases can arrive in this problem. One is when the consecutive element are same, one in which consecutive elements differ by one, one in which they differ by 2 and one in which they differ by more than 2. I solve this problem for all those cases.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nI will keep three variables pot(short for potential), notPot and helper. So basically if all consecutive numbers in the sorted array have a difference of one and then we get a number who is 2 value greater than the previous number, we can raise the value of all the numbers in our list by one to continue the pattern. So they have the potential of raising themself by one to continue the pattern.\n\nNow if we find a repeating number, we place the value of helper as one as it can help the pattern add an extra element to the pattern. Also we will put the value of pot in nonPot as now the pattern again has the potential of raising itself to continue the pattern.\n\nThe other two casses are less complex and understandable.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    int maxSelectedElements(vector<int>& nums) {\n        int n = nums.size();\n        sort(nums.begin(),nums.end());\n        int helper = 0, maxi = 1;\n        int pot = 1, notPot = 1;\n        \n        for(int i=0; i<n; i++) cout << nums[i] << endl;\n\n        for(int i=1; i<n; i++)\n        {\n            while(i<n && nums[i]==nums[i-1])\n            {\n                i++;\n                helper = 1;  \n                pot = max(pot,notPot);              \n            }\n\n            maxi = max(maxi,max(notPot,pot+helper));\n            \n            if(i<n){\n                if(nums[i]==nums[i-1]+1)\n                {\n                    pot++; notPot++;\n                }\n                else if(nums[i]==nums[i-1]+2)\n                {\n                    notPot = pot+1+helper;\n                    pot = 1;\n                    helper = 0;\n                }\n                else\n                {\n                    notPot = 1; \n                    pot = 1;\n                    helper = 0;\n                }\n            }\n            \n            maxi = max(maxi,max(notPot,pot+helper));\n        }\n        \n        return max(maxi, max(pot+helper, notPot));\n\n    }\n};\n```
['C++']