2813. 子序列最大优雅度
题目链接:2813. 子序列最大优雅度
代码如下:
//参考:https://leetcode.cn/problems/maximum-elegance-of-a-k-length-subsequence/solutions/2375128/fan-hui-tan-xin-pythonjavacgo-by-endless-v2w1
class Solution
{
public:long long findMaximumElegance(vector<vector<int>>& items, int k) {//把利润从大到小排序ranges::sort(items,[](const auto& a,const auto& b){return a[0]>b[0];});long long res=0,total_profit=0;unordered_set<int> vis;stack<int> duplicate;//重复类别的利润for(int i=0;i<items.size();i++){int profit=items[i][0],category=items[i][1];if(i<k){total_profit+=profit;//累加前k个项目的利润if(!vis.insert(category).second)//插入失败,证明是重复的{duplicate.push(profit);}}else if(!duplicate.empty()&&vis.insert(category).second)//碰到新的类型{total_profit+=profit-duplicate.top();//选一个重复类别中的最小利润替换duplicate.pop();}res=max(res,(long long)(total_profit+vis.size()*vis.size()));}return res;}
};