Maintain 2 DP .
Intuition\n Describe your first thoughts on how to solve this problem. \nKeep 2 Dp in One maintain that with using the ith element other without Using that elem
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nKeep 2 Dp in One maintain that with using the ith element other without Using that element i.e. use incremented (i-1) element.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nKeep 2 Dp in One maintain that with using the ith element other without Using that element i.e. use incremented (i-1) element.\n# Complexity\n- Time complexity: O(MaxElement + 1 )\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(MaxElement + 1 )\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    int maxSelectedElements(vector<int>& nums) {\n        /*\n        posWithoutUsing[i] = \n        dpWithoutUsing[i] =\n            if freq[i-1]>=2 : dpWithoutUsing[i] = max(dpWithUsing[i-1] , dpWithoutUsing[i-1]) +1 .\n            if freq[i-1] == 1 : dpWithoutUsing[i] =  dpWithoutUsing[i-1] +1 .\n            else : 0\n        dpWithUsing[i] = \n            if freq[i] --> dpWithUsing[i] = max(dpWithUsing[i-1] , dpWithoutUsing[i-1]) +1 .\n            else 0 \n        */\n        \n        const int mx = *max_element(nums.begin(), nums.end() ) +1 ;\n        const int n = mx;\n        vector<int> freq(n+1,0) ;\n        vector<int> dpWithoutUsing(n+1,0) ,dpWithUsing(n+1,0) ;\n        for(const int& i: nums) freq[i]++;\n        for(int i=1;i<=n;i++) {\n            \n            // update dpWithoutUsing\n            if(freq[i-1] >= 2) dpWithoutUsing[i] = max(dpWithUsing[i-1] , dpWithoutUsing[i-1]) +1 ;\n            else if(freq[i-1] == 1) dpWithoutUsing[i] =  dpWithoutUsing[i-1] +1 ;\n            else dpWithoutUsing[i] = 0;\n            \n            \n            // update dpWithUsing\n            \n            if(freq[i]) dpWithUsing[i] = max(dpWithUsing[i-1] , dpWithoutUsing[i-1]) +1 ;\n            else dpWithUsing[i] = 0;\n            \n        }\n        \n        return max( *max_element(dpWithoutUsing.begin(), dpWithoutUsing.end() ) ,* max_element(dpWithUsing.begin(), dpWithUsing.end() ) );\n        \n    }\n};\n```
['C++']