Beats 100% Java Solution
Guys detailed solution will come tomorrow ( If I get time )\n\n# Approach\nIf I sort the array, I can make sure that previous will always be lesser, So if I add
Guys detailed solution will come tomorrow ( If I get time )\n\n# Approach\nIf I sort the array, I can make sure that previous will always be lesser, So if I add 1 to prev I should get current one to continue my streak.\nBut here we can add 1 to any number, so what if previous was already incremented by 1 or what if it is not incremented.\n\nSo I will have two state for the previous one.\n\ndp[i][0] -> don\'t increment the current by 1\ndp[i][1] -> increment the current by 1\ndp[i-1][0] -> previous was not incremented\ndp[i-1][1] -> previous was incremented\n\n```Java []\nclass Solution {\n    public int maxSelectedElements(int[] nums) {\n        Arrays.sort(nums);\n        int n = nums.length;\n        int[][] dp = new int[n][2];\n        dp[0][0] = 1;\n        dp[0][1] = 1;\n        for(int i=1;i<n;i++) {\n            dp[i][0] = nums[i] == nums[i-1] + 1 ? 1 + dp[i-1][0] :\n                (nums[i] == nums[i-1] + 2 ? 1 + dp[i-1][1] : \n                (nums[i] == nums[i-1]) ? dp[i-1][0] : 1);\n            dp[i][1] = nums[i] == nums[i-1] ? 1 + dp[i-1][0] :\n                 (nums[i] == nums[i-1] + 1 ? 1 + dp[i-1][1] : 1);\n            if(nums[i] == nums[i-1]) {\n                dp[i][0] = dp[i-1][0];\n            }\n        }\n\n        int ans = 0;\n        for(int[] d: dp) {\n            ans = Math.max(ans, Math.max(d[0], d[1]));\n        }\n        return ans;\n    }\n}\n```\n\nNow here I can see I just care about previous two states, so I can store them in two variables to remove space.\n\n# Complexity\n- Time complexity: O(nlogn) -> sorting\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 {\n    public int maxSelectedElements(int[] nums) {\n        Arrays.sort(nums);\n        int n = nums.length;\n        int a = 1;\n        int b = 1;\n        int ans = 1;\n        for(int i=1;i<n;i++) {\n            int c = nums[i] == nums[i-1] + 1 ? 1 + a :\n                (nums[i] == nums[i-1] + 2 ? 1 + b :\n                (nums[i] == nums[i-1]) ? a : 1);\n            int d = nums[i] == nums[i-1] ? 1 + a :\n                 (nums[i] == nums[i-1] + 1 ? 1 + b : 1);\n            a = c;\n            b = d;\n            ans = Math.max(ans, Math.max(a, b));\n        }\n        return ans;\n    }\n}\n```\n\n# Complexity\n- Time complexity: O(nlogn) -> sorting\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)$$ -->
['Java']