2023/10/18

97 阅读1分钟

2530. 执行 K 次操作后的最大分数

算法掌握:

  • 贪心
  • 优先队列

解题思路:

利用api优先队列的自动插入有序队列里即可(语法题)

c++ 优先队列文档

java 优先队列文档

java code:

class Solution {
    public long maxKelements(int[] nums, int k) {
        PriorityQueue<Integer> queue = new PriorityQueue<Integer>((a, b) -> b - a);
        for (int num : nums) queue.offer(num);
        long res = 0;
        for (int i = 0; i < k; ++i) {
            int x = queue.poll();
            res += x;
            queue.offer((int)Math.ceil(x / 3.0));
        }
        return res;
    }
}

c++ code:

class Solution {
public:
    long long maxKelements(vector<int>& nums, int k) {
        priority_queue<int> queue(nums.begin(), nums.end());
        long long res = 0;
        for (int i = 0; i < k; i++) {
            int x = queue.top();
            queue.pop();
            res += x;
            queue.push((int)ceil(x / 3.0));
        }
        return res;
    }
};