Sorting | C++ | VERY EASY | TIME: O(N log(N)) | SPACE: O(1)
Approach\n Describe your approach to solving the problem. \nInitially sorting is done to make the sequence non-decreasing\n\nCase 1: If we do not increment the 
# Approach\n<!-- Describe your approach to solving the problem. -->\nInitially sorting is done to make the sequence non-decreasing\n\n**Case 1: If we do not increment the value of element by 1**\nprev1 at index i refers to max number of consucutive elements possible till index i in which **a[i]** is the last element.\n\n**Case 2: If we increment the value of element by 1**\nprev2 at index i refers to max number of consucutive elements possible till index i in which **a[i]+1** is the last element.\n\ntaking max of both prev1 and prev2 for answer\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(1)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    int maxSelectedElements(vector<int>& a) {\n        sort(a.begin(), a.end());\n        int ans = 1;\n\n        int prev1 = 1, prev2 = 1;\n        for (int i = 1; i < a.size(); i++) {\n            if (a[i] == a[i - 1]) {\n                prev2 = max(prev1 + 1, prev2);\n            }\n                else if (a[i] == (a[i - 1] + 1)) {\n                prev1 = max(prev2, prev1 + 1);\n                prev2 = prev2 + 1;\n\n            } else if (a[i] == (a[i - 1] + 2)) {\n                prev1 = prev2 + 1;\n                prev2 = 1;\n            } else {\n                prev1 = 1;\n                prev2 = 1;\n            }\n\n            ans = max(ans, prev1);\n            ans = max(ans, prev2);\n        }\n\n        return ans;\n    }\n};\n```
['C++']