Java binary search dp
\nclass Solution {\n    public int maxSelectedElements(int[] nums) {\n        Arrays.sort(nums);\n        int[][] memo = new int[nums.length][2];\n        for (
```\nclass Solution {\n    public int maxSelectedElements(int[] nums) {\n        Arrays.sort(nums);\n        int[][] memo = new int[nums.length][2];\n        for (int i = 0; i < nums.length; i++) {\n            Arrays.fill(memo[i], -1);\n        }\n        int ans = 0;\n        for (int i = 0; i < nums.length; i++) {\n\t\t    // start from each i\n            ans = Math.max(ans, Math.max(dfs(nums, i, 0, memo), dfs(nums, i, 1, memo)) + 1);\n        }\n        return ans;\n    }\n    \n    int dfs(int[] nums, int i, int plus, int[][] memo) {\n        if (i == nums.length) {\n            return 0;\n        }\n        if (memo[i][plus] != -1) {\n            return memo[i][plus];\n        }\n        int ans = 0;\n        int cur = nums[i] + plus;\n        // next = cur\n        int l = i + 1;\n        int r = nums.length;\n        while (l < r) {\n            int mid = l + (r - l) / 2;\n            if (nums[mid] < cur) {\n                l = mid + 1;\n            } else {\n                r = mid;\n            }\n        }\n        if (l < nums.length && nums[l] == cur) {\n            ans = Math.max(ans, dfs(nums, l, 1, memo) + 1);\n        }\n        // next > cur\n        l = i + 1;\n        r = nums.length;\n        while (l < r) {\n            int mid = l + (r - l) / 2;\n            if (nums[mid] <= cur) {\n                l = mid + 1;\n            } else {\n                r = mid;\n            }\n        }\n        if (l < nums.length && nums[l] == cur + 1) {\n            ans = Math.max(ans, dfs(nums, l, 0, memo) + 1);\n        }\n        memo[i][plus] = ans;\n        return ans;\n    }\n}\n```
[]