前言
每次都取最大值的策略我是知道的,排序的时间复杂度太高,用栈也不行。没想到c++
里面已经内置了优先队列priority_queue
代码
#include<iostream>
#include<algorithm>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
class Solution {
public:
long long maxKelements(vector<int>& nums, int k)
{
long long ans = 0;
priority_queue<int,vector<int>,less<int>>
maxQueue(nums.begin(), nums.end());
int topNum;
for (int i = 0; i < k; ++i)
{
if (maxQueue.empty() == false) {
topNum = maxQueue.top();
ans += topNum;
maxQueue.pop();
maxQueue.push(ceil(topNum * 1.0 / 3));
}
}
return ans;
}
};
int main()
{
Solution s;
vector<int> nums{ 1,10,3,3,3 };
cout << s.maxKelements(nums, 3) << endl;
return 0;
}