LeetCode每日一题——2558. Take Gifts From the Richest Pile

文章目录

一、题目

2558. Take Gifts From the Richest Pile

You are given an integer array gifts denoting the number of gifts in various piles. Every second, you do the following:

Choose the pile with the maximum number of gifts.

If there is more than one pile with the maximum number of gifts, choose any.

Leave behind the floor of the square root of the number of gifts in the pile. Take the rest of the gifts.

Return the number of gifts remaining after k seconds.

Example 1:

Input: gifts = [25,64,9,4,100], k = 4

Output: 29

Explanation:

The gifts are taken in the following way:

  • In the first second, the last pile is chosen and 10 gifts are left behind.
  • Then the second pile is chosen and 8 gifts are left behind.
  • After that the first pile is chosen and 5 gifts are left behind.
  • Finally, the last pile is chosen again and 3 gifts are left behind.
    The final remaining gifts are [5,8,9,4,3], so the total number of gifts remaining is 29.
    Example 2:

Input: gifts = [1,1,1,1], k = 4

Output: 4

Explanation:

In this case, regardless which pile you choose, you have to leave behind 1 gift in each pile.

That is, you can't take any pile with you.

So, the total gifts remaining are 4.

Constraints:

1 <= gifts.length <= 103

1 <= gifts[i] <= 109

1 <= k <= 103

二、题解

由于每次都需要重复"取最大值"的操作,因此使用最大堆进行存储,优化时间复杂度

cpp 复制代码
class Solution {
public:
    long long pickGifts(vector<int>& gifts, int k) {
        priority_queue<int> q(gifts.begin(),gifts.end());
        while(k--){
            int tmp = q.top();
            q.pop();
            q.push(int(sqrt(tmp)));
        }
        long long res = 0;
        while(!q.empty()){
            res += q.top();
            q.pop();
        }
        return res;
    }
};
相关推荐
小鱼在乎几秒前
动态规划---最长回文子序列
算法·动态规划
jimmy.hua1 分钟前
C++刷怪笼(5)内存管理
开发语言·数据结构·c++
xiaobai12 35 分钟前
二叉树的遍历【C++】
开发语言·c++·算法
DieSnowK11 分钟前
[项目][WebServer][Makefile & Shell]详细讲解
开发语言·c++·http·makefile·shell·项目·webserver
Freak嵌入式12 分钟前
全网最适合入门的面向对象编程教程:50 Python函数方法与接口-接口和抽象基类
java·开发语言·数据结构·python·接口·抽象基类
吱吱鼠叔29 分钟前
MATLAB数学规划:2.线性规划
算法·机器学习·matlab
声学黑洞仿真工作室37 分钟前
Matlab Delany-Bazley和Miki模型预测多孔材料吸声性能
开发语言·人工智能·算法·matlab·微信公众平台
机器学习之心41 分钟前
选址模型 | 基于混沌模拟退火粒子群优化算法的电动汽车充电站选址与定容(Matlab)
算法·选址模型
MogulNemenis1 小时前
力扣春招100题——队列
数据结构·算法·leetcode
dc爱傲雪和技术1 小时前
在 VS Code 中调试 C++ 项目
开发语言·c++