Java Beginner  100% TC: O(n) Solution + comments
Time & Space complexity: O(n)\n\nclass Solution {\n    public int maxSelectedElements(int[] nums) {\n        int min = Integer.MAX_VALUE, max = Integer.MIN_VALU
**Time & Space complexity:** O(n)\n```\nclass Solution {\n    public int maxSelectedElements(int[] nums) {\n        int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;\n        for(int num: nums) {\n            min = Math.min(min, num);\n            max = Math.max(max, num);\n        }\n        //added 4 extra to `n` to handle dp[i-2] where max consecutive is stored for `i`\n        //and one more case last `num` is duplicated then we can go 1 steps forward using num+1\n        int n = max-min+4;  \n        int[] dp =new int[n], freq = new int[n];\n        for(int num: nums) {\n            //num-min+2 is added to avoid checking if `i` is in boundary while checking dp[i-2]\n            freq[num-min+2]++;\n        }\n        // consecutive elements found so far without using duplicate `num` to extend the range\n        //(eg) [6,7,8,9,10,10] = here dp[0]=1, dp[1]=2, dp[2]=3, dp[3]=4, dp[4]=5, dp[5]=0\n        //dp[5]=0, because 10 is not a consecutive element but its a duplicate\n        int consecutive = 0, \n\n        // soFar stores max result along with previous consecutives if found\n        soFar = 0, \n        \n        //by default every element contributes to answer\n        answer = 1, \n        \n        //started with 2, because to handle dp[i-2] case\n        i = 2, \n        //states that do i have element from previous duplicate\n        //if found, I can use the element for the next index to extend the range\n        //(eg) [10, 10] -> here 10 frequency is 2 \n        //if I use 10, 11 then range becomes 2\n        extra = 0;\n\n        while(i<n) {\n            if(extra!=0) { // more than 1 element found previously\n                extra = freq[i]>0 ? 1: 0;\n                soFar++;\n            } else if(freq[i]!=0) { \n                //whenever soFar==0, it indicates that we are starting to see next element \n                //and  can\'t link with previous\n                //(eg) [7,8, 10, 11] - here soFar==0, when i=2, which is 10\n                //so try to get previous consecutive and move all the preivous element by 1 to prepend with 10\n                //(eg) [7,8, 10, 11] become -> [8,9,10,11], incremented 7+1, 8+1\n                soFar = soFar==0? dp[i-2] : soFar;\n                soFar++;\n                extra = freq[i]>1 ? 1 : 0;\n            } else {    //empty slots\n                soFar = extra = 0;\n            }\n            consecutive = freq[i]!=0 ? consecutive+1 : 0;\n            dp[i]=consecutive;\n            answer = Math.max(answer, soFar);\n            i++;\n        }\n        return answer;\n    }\n}\n```\nPlease **UPVOTE** if you find the solution helpful
['Java']