Sorting + Hashmap - Very simple
First, we sort the array. After that we can consider each element from left to right:\n\n1. If we increase the current element to  nums[i] + 1 then we can incre
First, we sort the array. After that we can consider each element from left to right:\n\n1. If we increase the current element to  `nums[i] + 1` then we can increase previous chain that ends in value `nums[i]`.\n2. If we don\'t increase the current element then we can extend previous chain that ends in `nums[i] - 1`.\n\nThe only thing we need to be careful is that we first check for case 1 and then case 2 (because otherwise we could use the current element twice - first to extend chain ending with `nums[i] - 1` and then with `nums[i]`).\n\nSorting is necessary because we first need to process all elements `< nums[i]` to get the longest chains.\n\nTime complexity: $\\mathcal{O}(nlog(n))$\nSpace complexity: $\\mathcal{O}(n)$\n\n# Code\n```\n#include <vector>\n#include <unordered_map>\n#include <algorithm>\n#include <iostream>\n\nusing namespace std;\n\nclass Solution {\npublic:\n    int maxSelectedElements(vector<int>& nums) {\n        sort(nums.begin(), nums.end());\n        unordered_map<int,int> lEnd;\n\n        const int n = nums.size();\n        int answer = 1;\n        for (int i = 0; i < n; ++i) {\n            int c = nums[i];\n\n            if (lEnd.find(c) != lEnd.end()) {\n                lEnd[c+1] = 1 + lEnd[c];\n                answer = max(lEnd[c+1], answer);\n            } else {\n                lEnd[c+1] = 1;\n            }\n\n            if (lEnd.find(c-1) != lEnd.end()) {\n                lEnd[c] = 1 + lEnd[c-1];\n                answer = max(lEnd[c], answer);\n            } else {\n                lEnd[c] = 1;\n            }\n        }\n\n        return answer;\n    }\n};\n```
['Hash Table', 'Sorting', 'C++']