Easy Iterative Dp solution using map
here is normal 2d-dp for reference but it gives tle.\n\n\nclass Solution {\npublic:\n    int maxSelectedElements(vector<int>& nums) {\n        sort(nums.begin()
here is normal 2d-dp for reference but it gives tle.\n\n```\nclass Solution {\npublic:\n    int maxSelectedElements(vector<int>& nums) {\n        sort(nums.begin(), nums.end());\n        int n = nums.size();\n\n        vector<vector<int> > dp(n, vector<int> (2, 1));\n\n        int ans = 1;\n        for(int i = 1; i < n; i++){\n            for(int j = 0; j < i; j++){\n                if(nums[i] == nums[j]+1){\n                    dp[i][0] = max(dp[i][0], dp[j][0]+1);\n                    dp[i][1] = max(dp[i][1], dp[j][1]+1);\n                }\n                else if(nums[i] == nums[j]){\n                    dp[i][1] = max(dp[i][1], dp[j][0]+1);\n                    \n                }\n                else if(nums[i] == nums[j]+2){\n                    dp[i][0] = max(dp[i][0], dp[j][1]+1);\n                }\n            }\n            ans = max({ans, dp[i][0], dp[i][1]});\n        }\n\n        return ans;\n    }\n};\n\n```\n\nadding an optimisation using maps we can solve it under time limit\n\n# Code\n```\nclass Solution {\npublic:\n    int maxSelectedElements(vector<int>& nums) {\n        sort(nums.begin(), nums.end());\n        int n = nums.size();\n\n        vector<vector<int> > dp(n, vector<int> (2, 1));\n\n        int ans = 1;\n        map<int, int> mp1, mp2;\n        mp1[nums[0]] = 1;\n        mp2[nums[0]] = 1;\n        for(int i = 1; i < n; i++){\n            dp[i][0] = max(dp[i][0], mp1[nums[i]-1]+1);\n            dp[i][1] = max(dp[i][1], mp2[nums[i]-1]+1);\n            dp[i][1] = max(dp[i][1], mp1[nums[i]]+1);\n            dp[i][0] = max(dp[i][0], mp2[nums[i]-2]+1);\n\n            mp1[nums[i]] = max(mp1[nums[i]], dp[i][0]);\n            mp2[nums[i]] = max(mp2[nums[i]], dp[i][1]);\n            ans = max({ans, dp[i][0], dp[i][1]});\n        }\n\n        return ans;\n    }\n};\n```
['C++']