Sorting + Greedy
\n# Code\n\nclass Solution {\npublic:\n    long long findMaximumElegance(vector<vector<int>>& v, int k) {\n        int n = v.size();\n        sort(v.begin(), v.
\n# Code\n```\nclass Solution {\npublic:\n    long long findMaximumElegance(vector<vector<int>>& v, int k) {\n        int n = v.size();\n        sort(v.begin(), v.end(), greater<vector<int>>());\n        long long ans = 0, answer = 0;\n        vector<int> duplicate;\n        set<int> visited;\n        for(int i=0;i<n;i++){\n            if(i < k){\n                ans += v[i][0];\n                if(visited.find(v[i][1]) != visited.end()){\n                    duplicate.push_back(v[i][0]);\n                }\n                visited.insert(v[i][1]);\n            }\n            else{\n                if(visited.find(v[i][1]) != visited.end()){\n                    continue;\n                }\n                else{\n                    if(((int)duplicate.size()) == 0){\n                        break;\n                    }\n                    ans -= ((duplicate.back()) - v[i][0]);\n                    duplicate.pop_back();\n                    visited.insert(v[i][1]);\n                }\n            }\n            int sz = visited.size();\n            answer = max(answer, ans + (1ll * sz * sz));\n        }\n\n        return answer;\n    }\n};\n```
['C++']