Skip to content

Maximize Consecutive Elements in an Array After Modification⚓︎

Link

Solution⚓︎

See reference (Chinese).

class Solution {
public:
    int maxSelectedElements(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        unordered_map<int, int> f;
        for (int x : nums) {
            f[x + 1] = f[x] + 1;
            f[x] = f[x - 1] + 1;
        }

        int ans = 0;
        for (auto& [_, res] : f) {
            ans = max(ans, res);
        }
        return ans;
    }
};

Another way of writing:

class Solution {
public:
    int maxSelectedElements(vector<int>& nums) {
        int n = nums.size();
        sort(nums.begin(), nums.end());

        vector<int> f(1e6 + 10);
        f[nums[0]] = 1;
        f[nums[0] + 1] = 1;
        for (int i = 1; i < n; i++) {
            f[nums[i] + 1] = f[nums[i]] + 1;
            f[nums[i]] = f[nums[i] - 1] + 1;
        }

        int ans = 0;
        for (int i = 0; i < 1e6 + 5; i++) {
            ans = max(ans, f[i]);
        }
        return ans;
    }
};