C++ Most Optimal and Concise Solution with Comments and Explanation!
Please upvote if you found this helpful!\n\n# Code\n\nclass Solution {\npublic:\n    int maximumSetSize(vector<int>& nums1, vector<int>& nums2) {\n        // se
Please upvote if you found this helpful!\n\n# Code\n```\nclass Solution {\npublic:\n    int maximumSetSize(vector<int>& nums1, vector<int>& nums2) {\n        // set1 is the number of unique elements that will be remaining after removal in nums1 (max size will be n/2)\n        // set2 is the number of unique elements that will be remaining after removal in nums2 (max size will be n/2)\n        // both is the number of elements that overlap in nums1 & nums2\n        int set1 = 0, set2 = 0, both = 0, n = nums1.size();\n        unordered_set<int> allNums1, allNums2;\n        for (int num: nums1) allNums1.insert(num);\n        for (int num: nums2) allNums2.insert(num);\n\n        // greedily add all unique nums in nums1 to set1\n        // and add all of the overlap to both\n        for (int num: allNums1) {\n            if (allNums2.find(num) == allNums2.end()) ++set1;\n            else ++both;\n        }\n        set1 = std::min(set1, n/2); // you can only have at most n/2\n\n        // greedily add all unique nums in nums2 to set2\n        for (int num: allNums2) {\n            if (allNums1.find(num) == allNums1.end()) ++set2;\n        }\n        set2 = std::min(set2, n/2); // you can only have at most n/2\n\n        // add as many of "both" to set1 to get it as high as n/2\n        if (set1 < n/2) {\n            int need = n/2 - set1;\n            int use = std::min(need, both);\n            set1 += use;\n            both -= use;\n        }\n\n        // add as many of "both" to set2 to get it as high as n/2\n        if (set2 < n/2) {\n            int need = n/2 - set2;\n            int use = std::min(need, both);\n            set2 += use;\n            both -= use;\n        }\n\n        return set1 + set2;\n    }\n};\n```
['C++']