Sort | Iterative | Beats 100%
\n# please Upvote If you like the solution\n# Code\n\nclass Solution {\n    public int maxSelectedElements(int[] nums) \n    {\n        Arrays.sort(nums);\n    
\n# please Upvote If you like the solution\n# Code\n```\nclass Solution {\n    public int maxSelectedElements(int[] nums) \n    {\n        Arrays.sort(nums);\n        int maxElements = 1;\n        int currentElements = 1;\n        int lastElement = nums[0];\n        int doubleCount = 0;\n        for (int i = 1; i < nums.length; i++) {\n            if (nums[i] - lastElement == 1) {\n                currentElements++;\n                lastElement = nums[i];\n            } else if (nums[i] - lastElement == 2) {\n                if (doubleCount == 1) {\n                    currentElements += 2;\n                    lastElement = nums[i];\n                    doubleCount = 0;\n                } else {\n                    currentElements += doubleCount;\n                    lastElement = nums[i];\n                    doubleCount = 0;\n                    maxElements = Math.max(maxElements, currentElements);\n                    currentElements = 2;\n                    int j = i - 2;\n                    while (j >= 0) {\n                        if (nums[j + 1] - nums[j] == 1) {\n                            currentElements++;\n                            j--;\n                        } else break;\n                    }\n                }\n            } else if (nums[i] - lastElement == 0) {\n                doubleCount = 1;\n            } else {\n                currentElements += doubleCount;\n                doubleCount = 0;\n                maxElements = Math.max(maxElements, currentElements);\n                currentElements = 1;\n                lastElement = nums[i];\n            }\n        }\n        currentElements += doubleCount;\n        maxElements = Math.max(maxElements, currentElements);\n        return maxElements;\n        \n        \n    }\n}\n```
['Java']