C++ O(N log N) Solution with Explanation
Intuition\n Describe your first thoughts on how to solve this problem. \nSince the order of elements is not important, sort the array. We will process from the 
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince the order of elements is not important, sort the array. We will process from the smallest to largest number. For each number nums[i], we can either use nums[i] or nums[i]+1 to expand a sequence. Store dp[j] where dp[j] is the length of the longest sequence with last element of value j. If we cannot expand from the previous numbers, the current length is 1. The answer is the maximum of any dp value we calculate. In my code, I calculate in the order below so that I do not accidentally use the current number twice by expanding a sequence with both nums[i] and nums[i]+1.\n\ndp(nums[i]+1) = max(1, dp(nums[i])+1) (continue using nums[i]+1, expand from nums[i])\ndp(nums[i]) = max(1, dp(nums[i]-1)+1) (continue using nums[i], expand from nums[i]-1)\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSort then loop through each element. Use an array to mantain the dp values.\n\n# Complexity\n- Time complexity: $$O(n log n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    int ans = 0;\n    int dp[1000005];\n    int maxSelectedElements(vector<int>& nums) {\n        sort(nums.begin(), nums.end());\n        for(int i = 1; i <= nums.size(); i++){\n            dp[nums[i-1]+1] = max(1, dp[nums[i-1]]+1);\n            dp[nums[i-1]] = max(1, dp[nums[i-1]-1]+1);\n            ans = max(ans, dp[nums[i-1]]);\n            ans = max(ans, dp[nums[i-1]+1]);\n        }\n        return ans;\n    }\n};\n```
['C++']