JAVA MEMOIZATION CAUSING TLE
\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\n\nclass Solution {\n    // Memoization HashMap\n    Map<String, Integer> memo;\n\n
```\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\n\nclass Solution {\n    // Memoization HashMap\n    Map<String, Integer> memo;\n\n    int solve(int ind, int[] nums, int prev) {\n        if (ind >= nums.length) {\n            return 0;\n        }\n        // Construct the key for the current subproblem\n        String key = ind + "_" + prev;\n        // If the subproblem is already computed, return the result from memo HashMap\n        if (memo.containsKey(key)) {\n            return memo.get(key);\n        }\n\n        int take = 0;\n        if (prev == -1) {\n            take = Math.max(1 + solve(ind + 1, nums, nums[ind]), (1 + solve(ind + 1, nums, nums[ind] + 1)));\n        } else if (nums[ind] - prev == 0 || nums[ind] - prev == 1) {\n            take = 1 + solve(ind + 1, nums, (nums[ind] - prev == 0 ? nums[ind] + 1 : nums[ind]));\n        }\n        int not = solve(ind + 1, nums, prev);\n        // Store the result in memo HashMap\n        memo.put(key, Math.max(take, not));\n        return memo.get(key);\n    }\n\n    public int maxSelectedElements(int[] nums) {\n        Arrays.sort(nums);\n        // Initialize memo HashMap\n        memo = new HashMap<>();\n        return solve(0, nums, -1);\n    }\n}\n```\n
['Dynamic Programming', 'Recursion', 'Memoization', 'Sorting', 'Java']