Java | Easy | Explanation ✅🔥
Intuition\nImagine a number n we can attach it with the list having n-1, so length of list will increase with n = 1 + length of n-1,\nfox ex n=8, we can attach 
# Intuition\nImagine a number `n` we can attach it with the list having `n-1`, so length of list will increase with n = 1 + length of n-1,\nfox ex n=8, we can attach 8 with 7, so the length of 8 ie equal to  whatever the length of till 7, increae by 1.\n\nn can also be n+1, so length till n+1 = 1+length of n.\n\n# Approach\n- Sort the input array `nums` in ascending order.\n- Initialize a variable `max` to 0 to store the maximum number of selected elements.\n- Create a HashMap named `map` to store frequencies of each number.\n- Iterate through each element `data` in the sorted `nums` array.\n- For each element `data`:\n  - Increment the frequency of `data+1` in the map by 1 if it exists, otherwise, put `data` with value 1.\n  - Increment the frequency of `data` in the map by 1 if it exists, otherwise, put `data-1` with value 1.\n  - Update the `max` variable with the maximum frequency between `data` and `data+1` in the map.\n- Return the maximum number of selected elements stored in `max`.\n# Complexity\n- Time complexity: $$O(n)$$\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 max = 0;\n        \n        Map<Integer, Integer> map = new HashMap();\n        for(int data: nums){\n            map.put(data+1, map.getOrDefault(data, 0)+1);\n            map.put(data, map.getOrDefault(data-1, 0)+1);\n            \n            max = Math.max(max, Math.max(map.get(data),map.get(data+1)));\n        }\n        \n        \n        \n        return max;\n    }\n}\n```
['Java']