2813. Maximum Elegance of a K-Length Subsequence
```\nclass Solution {\n public:\n  long long findMaximumElegance(vector>& items, int k) {\n    long long ans = 0;\n    long long totalProfit = 0;\n    // Store 
```\nclass Solution {\n public:\n  long long findMaximumElegance(vector<vector<int>>& items, int k) {\n    long long ans = 0;\n    long long totalProfit = 0;\n    // Store seen categories.\n    unordered_set<int> seenCategories;\n    // Store duplicate profits decreasingly.\n    stack<int> decreasingDuplicateProfits;\n\n    ranges::sort(items, greater<>());\n\n    for (int i = 0; i < k; i++) {\n      const int profit = items[i][0];\n      const int category = items[i][1];\n      totalProfit += profit;\n      if (seenCategories.count(category))\n        decreasingDuplicateProfits.push(profit);\n      else\n        seenCategories.insert(category);\n    }\n\n    ans = totalProfit + 1LL * seenCategories.size() * seenCategories.size();\n\n    for (int i = k; i < items.size(); ++i) {\n      const int profit = items[i][0];\n      const int category = items[i][1];\n      if (!seenCategories.count(category) &&\n          !decreasingDuplicateProfits.empty()) {\n        // If this is a new category we haven\'t seen before, it\'s worth\n        // considering taking it and replacing the one with the least profit\n        // since it will increase the distinct_categories and potentially result\n        // in a larger total_profit + distinct_categories^2.\n        totalProfit -= decreasingDuplicateProfits.top(),\n            decreasingDuplicateProfits.pop();\n        totalProfit += profit;\n        seenCategories.insert(category);\n        ans = max(ans, static_cast<long long>(totalProfit +\n                                              1LL * seenCategories.size() *\n                                                  seenCategories.size()));\n      }\n    }\n\n    return ans;\n  }\n};\n
['Hash Table']